How can I replace the "." in a float with "_" in python?

Question:

Python code (can’t change this):

import numpy as np
        
for VALUES in np.arange(0.1, 0.3, 0.1):
    print("Value: %s" % (VALUES))

Output:

Value: 0.1
Value: 0.2

Desired output:

Value: 0_1
Value: 0_2

I am a beginner when it comes to python, and I’m struggling with this simple task. Is this possible with the replace() method? Do I need to create a new function that makes the replacement?

Asked By: rookiecookie24

||

Answers:

It’s hard to tell given the limited information provided.

But if you want to make the replacement just for the code shown here you can do this:

import numpy as np
        
for VALUES in np.arange(0.1, 0.3, 0.1):
    print("Value: %s" % (str(VALUES).replace(".", "_")))

But I am not sure what you mean when you say "can’t change this".

Hope this gives a hint at least.

Answered By: jesperk.eth

It’s very simple to do, you need to convert the float to a string.

float_value = 0.1
string_value = str(float_value)

Then you can use the replace() function

string_value = string_value.replace(".","_")
Answered By: Lewis Herbert
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.