Home > Back-end >  How can I replace the "." in a float with "_" in python?
How can I replace the "." in a float with "_" in python?

Time:10-15

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?

CodePudding user response:

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.

CodePudding user response:

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(".","_")
  • Related