将unicode字符串转换为float

时间:2015-10-18 13:33:11

标签: python python-2.7 python-3.x unicode type-conversion

我的Python字符串>>> 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 又名“-20”和the Unicode minus sign

当试图转换为浮动时,我正在

>>> 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 2和

u'\u221220'

使用Python 3。

如何在Python 2和Python 3中正确地将-20.0转换为float {{1}}?便携式解决方案会很棒。

1 个答案:

答案 0 :(得分:1)

来自@ j-f-sebastian:

a = u'\u221220'
float(a.replace(u'\N{MINUS SIGN}', '-'))

诀窍。请参阅the related Python issue