How can I turn a string into a float?

Asked

Viewed 105 times

-1

I am doing a job and I came across the following situation: I have a list with decimal numbers. But the list is like a string. For example:

h = ["3,5","4,3","8,9"]

Now my problem appears, I need the string to become a float, to be able to realize an account similar to the one below:

#este trecho de código é apenas um exemplo da conta
p = [3.5, 20.4, 7.2]
y = 50
m = []
for i in range(len(p)):
    m.append(y/p[i])
print(m)

However I could notice that there are two problems. First the list h (which is a string) should be a float. And second, as we know, decimal numbers must be separated by "." when they are float.

I thought of the following situation. First I need to change the "," from the decimals to "." and with that I can quietly transform from str to float.

To change "," to "." I tried to use . replace as follows:

h = ["3,5","4,3","8,9"]
print(type(h))

h = str(h).strip("[]")
h = h.replace(",", ".")
print(type(h),h)

It ended up working too much, because all the commas were replaced. Including those that should be kept to make the separation. What I mean is:

<class 'list'>
<class 'str'> '3.5'. '4.3'. '8.9'     #esses foram os resultados dos prints

Then I tried to turn it into a float, but it won’t. I even tried to append an empty list to see if I could trasnformar in float, but always error.

h = ["3,5","4,3","8,9"]
print(type(h))
ju = []

h = str(h).strip("[]")
h = h.replace(",", ".")
h = float(h)                  #ValueError: could not convert string to float: "'3.5'. '4.3'. '8.9'"
print(type(h),h)                 # caso eu coloque a linha do h = float(h) em comentário,
                                 # aparece como none a nova lista
ju = ju.append(h)
print(type(ju))               #<class 'NoneType'> None

Now I’m stuck in it, I don’t know how to proceed. Please, I beg help from some Python guru.

  • That’s what you want? [str(float(i.replace(",", "."))) for i in h]

2 answers

2


If you want to turn every Aray value into a float, just do this:

h = [ float(x.strip("[]").replace(",", ".")) for x in h ]

For the face element of your array, you remove the spaces, change the comma to a point and turn it into a float, achieving an array of floats.

Besides, on the line where you do

h = float(h) 

You are trying to float an array instead of a string.

0

Another interesting way to resolve this issue is by using the following code:

h = ["3,5", "4,3", "8,9"]
m = [round(50 / float(i.replace(',', '.')), 2) for i in h]
print(m)

Note that when we execute this code the structure will be executed for of list comprehension. At this time the following instruction is executed: for i in h, magpie i, convert the comma - , - to point - .. Then take this value and convert it to float. Then performs the division of 50 / float() and then round the value to two decimal places.

After you have performed all these operations the list appears m, containing float values to two decimal places.

Observing

Once I realized the values produced by 50 / float would produce values with more than 6 decimal places, I decided to use the round() function to round the values to two decimal places.

  • I found it interesting, thank you for your help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.