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
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to