This code uses this logic:
- if not. or ',' are present, just convert to float
else if ',' or '.' are the third character from the end, then this is a decimal character:
. strip and then not a decimal character, change the decimal char character to '.' if necessary, then convert to float
yet
. there is no decimal part, just separate all "," and ".". and convert to float
This code is very dependent on getting valid strings - invalid strings like "1,2,3.000"
or "1..."
will give erroneous values.
def parse_price(s): if '.' not in s and ',' not in s: return float(s) elif s[-3] in ',.': dec_char = s[-3] sep_char = {'.': ',', ',':'.'}[dec_char] s = s.replace(sep_char, '') s = s.replace(',', '.') return float(s) else: s = s.replace(',','').replace('.', '') return float(s) tests = """\ 1.000 1.000,20 23.14 1,234 1.23 3,12 """.splitlines() for test in tests: print(test, '->', parse_price(test))
gives
1.000 -> 1000.0 1.000,20 -> 1000.2 23.14 -> 23.14 1,234 -> 1234.0 1.23 -> 1.23 3,12 -> 3.12
source share