String/Number Conversion

John Machin sjmachin at lexicon.net
Sat Sep 6 23:38:28 CEST 2008


On Sep 7, 7:04 am, Andreas Hofmann <asdfasdfasdfasdfa... at arcor.de>
wrote:
> Hello Folks!
>
> I've got a little problem here, which which really creeps me out at the
> moment.
> 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:
>
> def eliminate_postfix(value):
>          if type(value) is str:

Don't use "is" unless you are really sure that "==" won't do the job.
Better idiom:
if isinstance(value, str):

>                  value.upper()

This causes your "mult is always 1" problem. You need:
    value = value.upper()
Why? Because strings are immutable. String methods like upper return a
new string, they don't change the existing string.

>                  if value.endswith('K'):
>                          mult = 1000
>                  elif value.endswith('M'):
>                          mult = 1000000
>                  elif value.endswith('G'):
>                          mult = 1000000000
>                  else:
>                          mult = 1
>
>                  if mult is 1:

Lose "is". In fact, lose the whole "if" statement. See below.

>                          value = string.atoi(value)

Don't use deprecated functions from the string module. Use the built-
in float function to convert from text.

>                  else:
>                          value = string.atoi(value[:-1]) * mult
>          return value

Those last few statements look somewhat tortuous. Try this:
    else: # mult would be 1, but we don't need it
        return float(value)
    return float(value[:-1]) * mult

HTH,
John



More information about the Python-list mailing list