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:
JavaScript
x
2
1
float_regex = re.compile(r'[-.+d]+')
2
Find all of these characters in the input string and join them together:
JavaScript
1
2
1
clean_input = ''.join(float_regex.findall(input_string))
2
And only then convert to a float.
For example:
JavaScript
1
7
1
>>> import re
2
>>> float_regex = re.compile(r'[-.+d]+')
3
>>> input_string = '₹xa022,'
4
>>> clean_input = ''.join(float_regex.findall(input_string))
5
>>> float(clean_input)
6
22.0
7