You are replacing the first dot with a comma, after first replacing the first comma with a dot. The dot the first str.replace()
inserted is not exempt from being replaced by the second str.replace()
call.
Use the str.translate()
method instead:
try:
from string import maketrans # Python 2
except ImportError:
maketrans = str.maketrans # Python 3
price = price.translate(maketrans(',.', '.,'))
This'll swap commas for dots and vice versa as it traverses the string, and won't make double replacements, and is very fast to boot.
I made the code compatible with both Python 2 and 3, where string.maketrans()
was replaced by a the static str.maketrans()
function.
The exception here is Python 2 unicode
; it works the same as str.translate()
in Python 3, but there is no maketrans
factory to create the mapping for you. You can use a dictionary for that:
unicode_price = unicode_price.translate({u'.': u',', u',': u'.'})
Demo:
>>> try:
... from string import maketrans # Python 2
... except ImportError:
... maketrans = str.maketrans # Python 3
...
>>> price = "10.990,00"
>>> price.translate(maketrans(',.', '.,'))
'10,990.00'