我有 Python 字符串 u'\u221220'
aka "−20"with the Unicode minus sign .
当尝试转换成 float 时,我得到了
>>> a = u'\u221220'
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'decimal' codec can't encode character u'\u2212' in position 0: invalid decimal Unicode string
使用 Python 2 和
>>> a = u'\u221220'
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '−20'
使用 Python 3。
如何在 Python 2 和 Python 3 中将 u'\u221220'
正确转换为 float -20.0
?可移植解决方案会很棒。
最佳答案
来自@j-f-sebastian:
a = u'\u221220'
float(a.replace(u'\N{MINUS SIGN}', '-'))
成功了。参见 the related Python issue .
关于python - 将 unicode 字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33198510/