2015-10-18 214 views
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?便攜式解決方案將非常棒。

+0

作爲解決方法,將Unicode減號的所有出現置換爲常規號。此外,請提供解析器應該擴展的票據。它已經支持更多的數字,而不僅僅是普通的'0-9',所以增加對這種減號表示的支持應該是可能的。 –

+3

嘗試'float(a.replace(u'\ N {MINUS SIGN}',' - '))'作爲解決方法。請參閱[相關Python問題](http://bugs.python.org/issue10581#msg191011)。 – jfs

+0

@ J.F.Sebastian如果您將您的評論推薦給答案,我很樂意將其標記爲解決方案。 –

回答

1

從@ J-F-塞巴斯蒂安:

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

的伎倆。見the related Python issue

相關問題