-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]
– Paulo Marques