8

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'
PedroA
  • 1,803
  • 4
  • 27
  • 50
  • 2
    FWIW, you can use the standard `unicodedata` module to get the name of each char in string that's behaving mysteriously. Eg, if the string is `s` do `import unicodedata as ud` `print(*map(ud.name, s), sep=', ')`. See the module docs for more nifty functions. And of course you can do `print(s.encode('unicode-escape'))` – PM 2Ring Jul 23 '17 at 20:47

2 Answers2

26

Your string contains a unicode en-dash, not an ASCII hyphen. You could replace it:

>>> float('–1123.04'.replace('\U00002013', '-'))
-1123.04
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • 1
    You can throw [this](https://pastebin.com/hvm4yDpK) in there if you want to show the difference, if you like. – idjaw Jul 23 '17 at 20:35
  • can you explain how you see the exact unicode type. I have a slightly different dash and was wondering how to fix my issue – qwertylpc Sep 28 '19 at 15:34
  • 2
    @qwertylpc: See the comment on the question by Pm 2Ring. You can also use `.encode('unicode-escape')` to get a representation that will use backslash-escape representations for non-ASCII Unicode characters. – BrenBarn Sep 29 '19 at 21:02
2

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)
user2589273
  • 2,379
  • 20
  • 29