Python convert string to float error with negative numbers

Viewed 11074

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'
2 Answers

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)
Related