String/Number Conversion

Scott David Daniels Scott.Daniels at Acm.Org
Sat Sep 6 18:41:09 EDT 2008


Andreas Hofmann wrote:
> I've got some strings, which only contain numbers plus eventually one 
> character as si-postfix (k for kilo, m for mega, g for giga). I'm trying 
> to convert those strings to integers, with this function:

Why bother to always switch the case if you only use a few values?
Also, the Python style is to do an operation and handle failures, rather
than test first.

Try something like:

     _units = dict(K=1000, M=1000000, G=1000000000,
                   k=1000, m=1000000, g=1000000000)

     def eliminate_postfix(value):
         try:
             return _units[value[-1]] * int(value[: -1])
         except (TypeError, KeyError):
             return int(value)

If you normally do not have the suffixes, then switch it around:

     def eliminate_postfix(value):
         try:
             return int(value)
         except ValueError:
             return _units[value[-1]] * int(value[: -1])


If this is really SI units, you likely are doing real measurements,
so I'd consider using "float" instead of "int" in the above.


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list