Skip to main content
 首页 » 编程设计

python之将 unicode 字符串转换为 float

2025年05月04日23zlslch

我有 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 .