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'
1
  • 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')) Commented Jul 23, 2017 at 20:47

2 Answers 2

27

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

>>> float('–1123.04'.replace('\U00002013', '-'))
-1123.04
Sign up to request clarification or add additional context in comments.

3 Comments

You can throw this in there if you want to show the difference, if you like.
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: 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.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.