Remove currency symbols and literals from a string with a price universal solution

╄→гoц情女王★ 提交于 2020-01-03 03:07:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!