String/Number Conversion

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Sep 6 17:50:54 EDT 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
spaces.
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
overkill.


>                  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)
    1
    >>> el_post("100")
    100
    >>> el_post("")
    Traceback (most recent call last):
      ...
    ValueError: invalid literal for int() with base 10: ''
    >>> el_post("100g")
    100000000000L
    >>> el_post("100G ")
    100000000000L
    >>> el_post("100 G ")
    100000000000L
    >>> el_post("100hg")
    Traceback (most recent call last):
      ...
    ValueError: invalid literal for int() with base 10: '100H'
    >>> el_post(" 100  k  ")
    100000
    >>> el_post("  100m")
    100000000
    >>> el_post(u"100m")
    100000000
    """
    ... function code ...


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

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

Bye,
bearophile



More information about the Python-list mailing list