1
我有Python字符串u'\u221220'
又名“-20”与the Unicode minus sign。将unicode字符串转换为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
我怎样才能正确地转换u'\u221220'
成在Python 2和Python 3中float -20.0
?便携式解决方案将非常棒。
作为解决方法,将Unicode减号的所有出现置换为常规号。此外,请提供解析器应该扩展的票据。它已经支持更多的数字,而不仅仅是普通的'0-9',所以增加对这种减号表示的支持应该是可能的。 –
尝试'float(a.replace(u'\ N {MINUS SIGN}',' - '))'作为解决方法。请参阅[相关Python问题](http://bugs.python.org/issue10581#msg191011)。 – jfs
@ J.F.Sebastian如果您将您的评论推荐给答案,我很乐意将其标记为解决方案。 –