Removing redundant characters from a string

Let's say I have this line: '12,423,343.93'

. How can you transform it in a float

simple, efficient and elegant way?

It seems I need to remove redundant commas from a string and then invoke float()

, but I don't have a good solution for this.

thank

+2


source to share


2 answers


s = "12,423,343.93"
f = float(s.replace(",", ""))

      



+9


source


Please note that the separator characters used differ from country to country. In some cultures, "." used to separate groups, and "," means, for example, a decimal point. If you are parsing user-entered strings like this, it is better to use a local module. For example:



>>> import locale
>>> locale.atof('12,423,343.93')  # No locale set yet, so this will refuse to parse
ValueError: invalid literal for float(): 12,423,343.93   

>>> locale.setlocale(locale.LC_NUMERIC, "en_GB")  # Use a UK locale.
>>> locale.atof('12,423,343.93')
12423343.93

      

+6


source







All Articles