Skip to content
Advertisement

How to convert ₹22000 string to float in python

Traceback (most recent call last): File “scrap.py”, line 13, in converted_price=float(price[:5]) ValueError: could not convert string to float: ‘₹xa022,’

Advertisement

Answer

You’ll have to filter out all of the characters that aren’t part of a floating point number since the float function only allows certain characters.

You could use a regular expression (regex) to find all of the characters that are allowed in a floating point number. For example, to find all of the digits, minuses, pluses and dots:

float_regex = re.compile(r'[-.+d]+')

Find all of these characters in the input string and join them together:

clean_input = ''.join(float_regex.findall(input_string))

And only then convert to a float.

For example:

>>> import re
>>> float_regex = re.compile(r'[-.+d]+')
>>> input_string = '₹xa022,'
>>> clean_input = ''.join(float_regex.findall(input_string))
>>> float(clean_input)
22.0
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement