[Tutor] Help converting strings to numbers

Hans Nowak hnowak@cuci.nl
Tue, 28 Aug 2001 12:12:02 +0200


>===== Original Message From Charlie@begeistert.org =====
>Dear all,
>
>I'm getting a whole set of values and putting them in a dictionary like
>this
>
>{'preis': '2.029,00', 'marktpreis':'3.399,00'}
>
>from which I need to generate a third price 'saving' which is ('preis' /
>'marktpreis') * 100 but I don't know how to convert the string prices to
>floats to do the maths - it's an invalid literal.
>
>Please reply to me directly as I'm currently subscribed to the digest.

Not sure if there is a function for this in the standard library, but you can 
easily roll your own:

>>> import string
>>> s = '2.029,33'
>>> s = string.replace(s, ".", "")
>>> s
'2029,33'
>>> s = string.replace(s, ",", ".")
>>> s
'2029.33'
>>> float(s)
2029.3299999999999

HTH,

--Hans Nowak