Skip to content
Advertisement

Remove comma and change string to float

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

import locale,re
def currencyToFloat(x):
    empty = []
    reNum = re.compile(r"""(?P<prefix>$)?(?P<number>[.,0-9]+)(?P<suffix>s+[a-zA-Z]+)?""")
    new = reNum.findall(x)
    for i in new:
        i[1].replace(",", "")
        float(i[1])
        empty.append(i[1])
        empty.append(i[0])
    return empty

print currencyToFloat("$33,326")

Can you help me debug my code?

Advertisement

Answer

When you do

float(i[1])

you are not modifying anything. You should store the result in some variable, like:

temp = ...

But to cast to float your number have to have a dot, not a comma, so you can do:

temp = i[1].replace(",", ".")

and then cast it to float and append to the list:

empty.append(float(temp))

Note:

Something important you should know is that when you loop through a list, like

for i in new:

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:

for i in range(len(new)):
    new[i] = ...
Advertisement