我從HTML解析字符串:U '\ u2212 $ 9.02',( - $ 9.02)Python的Unicode轉換減號浮動
簡單地做一個浮動()轉換不起作用。 'decimal'編解碼器無法在位置0編碼字符u'\ u2212':無效的十進制Unicode字符串。
也許嘗試檢測字符串中的'\ u2212'?但那怎麼做呢?
任何想法如何做到這一點?
我從HTML解析字符串:U '\ u2212 $ 9.02',( - $ 9.02)Python的Unicode轉換減號浮動
簡單地做一個浮動()轉換不起作用。 'decimal'編解碼器無法在位置0編碼字符u'\ u2212':無效的十進制Unicode字符串。
也許嘗試檢測字符串中的'\ u2212'?但那怎麼做呢?
任何想法如何做到這一點?
你可以做
s = u'\u2212$9.02'
float(s.replace(u'\u2212', '-').replace('$', ''))
注意,美元符號也會引起問題。
您可以使用正則表達式:
import re
def currency_to_cents(s):
m = re.match(r"([−+]?)\$(\d+)(?:\.(\d+))?", s)
if m is None:
raise ValueError("{!r} is not correctly-formatted currency".format(s))
sign, dollars, cents = m.groups()
amount = int(dollars) * 100
if cents:
amount += int(cents)
if sign == "−":
amount = -amount
return amount
它通常是更好地管理貨幣作爲美分(或更小,如果需要的話),因爲浮點錯誤的。
對於貨幣,我更喜歡使用Decimal
模塊;而不是處理浮游物:
>>> from decimal import Decimal
>>> i = Decimal(s.replace(u'\u2212','-').replace('$',''))
>>> i
Decimal('-9.02')
您可能想知道爲什麼?您可以在電腦彩車的近似讀了起來,但在實踐中,這裏是小數更有意義的例子:
>>> 1.1 + 2.2
3.3000000000000003
>>> Decimal('1.1') + Decimal('2.2')
Decimal('3.3')
>>> 1.30 + 1.20
2.5
>>> Decimal('1.30') + Decimal('1.20')
Decimal('2.50')
十進制模塊上面的例子和其他用途從module documentation拍攝。