繁体   English   中英

将 unicode 字符串转换为浮点数

[英]convert unicode string to float

我有带有Unicode 减号的 Python 字符串u'\−20'又名“−20”。

当尝试转换为浮点数时,我得到

>>> 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'\−20'正确转换为浮点数-20.0 便携式解决方案会很棒。

来自@jf-sebastian:

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

诀窍。 请参阅相关的 Python 问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM