Remove comma and change string to float

Question:

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?

Asked By: neymar

||

Answers:

money = "$33,326"
money_list = [float("".join(money[1:].split(","))), "$"]
print(money_list)

OUTPUT

[33326.0, ‘$’]

Answered By: Ol' Reliable

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] = ...
Answered By: Christian Tapia

You can use str.translate()

>>>money= "$333,26"
>>>float(money.translate(None, ",$"))
33326.0

With Python 3 you can use str.maketrans with str.translate:

money = "$33,326"
print('money: {}'.format(float(money.translate(str.maketrans('', '', ",$")))))

Output: money: 33326.0

Answered By: frmbelz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.