Reputation: 1925
How to convert a negative number stored as string to a float?
Am getting this error on Python 3.6 and don't know how to get over it.
>>> s = '–1123.04'
>>> float(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '–1123.04'
Upvotes: 8
Views: 15765
Reputation: 2467
For a more generic solution, you can use regular expressions (regex) to replace all non-ascii characters with a hyphen.
import re
s = '–1123.04'
s = re.sub(r'[^\x00-\x7F]+','-', s)
s = float(s)
Upvotes: 2
Reputation: 251365
Your string contains a unicode en-dash, not an ASCII hyphen. You could replace it:
>>> float('–1123.04'.replace('\U00002013', '-'))
-1123.04
Upvotes: 27