String/Number Conversion

bearophileHUGS at bearophileHUGS at
Sat Sep 6 23:50:54 CEST 2008

Andreas Hofmann, there are several problems in your code:

>          if type(value) is str:

Better to use isinstance() and to compare it with basestring instead.

>                  value.upper()

This does nothing, python strings are immutable, so they don't get
changed in-place, so you have to assign that result to some name,
possibly a different name.
I also suggest you to strip the uppered string, to remove head/tail
Your indenting isn't much good, I suggest you to use only four spaces
for each indent (you can also use one tab, but I don't suggest this).

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

This is okay. You can also put those key-values in a dict, that you
can access with the get method with a default 1, but it may be

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

Instead of using string.atoi, use the int() builtin.

If you follow my suggestions you will have a function that works in
many situations. It will raise exceptions in other situations, but
that's good.

But to not need much of our help in your future code I suggest you to
use the Python shell and test every line you write. I also suggest you
to start right now using tests, for example like this:

def eliminate_postfix(value):
    >>> el_post = eliminate_postfix
    >>> el_post(1)
    >>> el_post("100")
    >>> el_post("")
    Traceback (most recent call last):
    ValueError: invalid literal for int() with base 10: ''
    >>> el_post("100g")
    >>> el_post("100G ")
    >>> el_post("100 G ")
    >>> el_post("100hg")
    Traceback (most recent call last):
    ValueError: invalid literal for int() with base 10: '100H'
    >>> el_post(" 100  k  ")
    >>> el_post("  100m")
    >>> el_post(u"100m")
    ... function code ...

if __name__ == "__main__":
    import doctest
    print "Doctests done.\n"

That will improve your coding a LOT, reducing your bug count, etc.


More information about the Python-list mailing list