问题
I have such examples:
USD 10.99
LIR10.99
$ 10.99
$10.99
So the input data may be any 'symbolfloat' or 'symbol float'.
I have made something like this:
float((str(param[2]).translate(None, '$USDLIR')))
But it can be any world currency, so it must be a universal converter.
回答1:
Remove anything from the string which isn't a digit or a decimal point:
import re
import locale
decimal_point_char = locale.localeconv()['decimal_point']
clean = re.sub(r'[^0-9'+decimal_point_char+r']+', '', str(param[2]))
value = float(clean)
That will also handle grouping ($ 1,000.00
) and different locales.
回答2:
You can remove everything except the number (including comma or decimal dot):
import re
trim = re.compile(r'[^\d.,]+')
mystring = 'USD 10.99'
result = trim.sub('', mystring)
print(result)
# '10.99'
回答3:
I just found a solution:
def price_convert(_price):
return float(sub(r'[^0-9.]', '', _price))
来源:https://stackoverflow.com/questions/27128253/remove-currency-symbols-and-literals-from-a-string-with-a-price-universal-soluti