String/Number Conversion
josh logan
dear.jay.logan at gmail.com
Sat Sep 6 17:27:11 EDT 2008
On Sep 6, 5:04 pm, 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:
> value.upper()
> 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:
> value = string.atoi(value)
> else:
> value = string.atoi(value[:-1]) * mult
> return value
>
> The problem is as follows: Everytime a string with a postfix should get
> converted, mult does not get set properly. It is always 1. Does anyone
> have an idea how to fix this? I just don't see it, maybe because I'm
> pretty new to python or because I'm just blind I would be really greatful.
>
> Kind regards,
> Andy
Hello,
1. You call value.upper(), but you do not capture the results of that
method. Strings are immutable in Python.
>> value = value.upper()
2. You should use == instead of "is" in the comparison of mult being
1.
>> if mult == 1:
More information about the Python-list
mailing list