I want to find “money” in a file and change the string
to float
, for example, I use regular expression to find “$33,326” and would like to change to [33326.0, “$”] (i.e., remove comma, $ sign and change to float
). I wrote the following function but it gives me an error
JavaScript
x
14
14
1
import locale,re
2
def currencyToFloat(x):
3
empty = []
4
reNum = re.compile(r"""(?P<prefix>$)?(?P<number>[.,0-9]+)(?P<suffix>s+[a-zA-Z]+)?""")
5
new = reNum.findall(x)
6
for i in new:
7
i[1].replace(",", "")
8
float(i[1])
9
empty.append(i[1])
10
empty.append(i[0])
11
return empty
12
13
print currencyToFloat("$33,326")
14
Can you help me debug my code?
Advertisement
Answer
When you do
JavaScript
1
2
1
float(i[1])
2
you are not modifying anything. You should store the result in some variable, like:
JavaScript
1
2
1
temp =
2
But to cast to float
your number have to have a dot, not a comma, so you can do:
JavaScript
1
2
1
temp = i[1].replace(",", ".")
2
and then cast it to float and append to the list:
JavaScript
1
2
1
empty.append(float(temp))
2
Note:
Something important you should know is that when you loop through a list, like
JavaScript
1
2
1
for i in new:
2
i
is a copy of each element, so if you modify it, no changes will be done in the list new
. To modify the list you can iterate over the indices:
JavaScript
1
3
1
for i in range(len(new)):
2
new[i] =
3