Search code examples
pythonregexstringconverterscurrency

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


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.


Solution

  • 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.