parsing engineering symbols

Fredrik Lundh fredrik at pythonware.com
Tue Dec 20 17:28:12 EST 2005


Suresh Jeevanandam wrote:

> I want to convert a string to float value. The string contains
> engineering symbols.
>
> For example,
>
> s = '12k'
>
> I want some function which would return 12000
> function(s)
> => 12000.0
> I searched the web, but could not find any function.

how about:

SI_prefixes = {
    'Y':24, 'Z':21, 'E':18, 'P':15, 'T':12, 'G':9, 'M':6, 'k':3,
    'h':2, 'd':-1, 'c':-2, 'm':-3, u'\xb5':-6, 'u':-6, 'n':-9, 'p':-12,
    'f':-15, 'a':-18, 'z':-21, 'y':-24
}

def myfloat(str):
    try:
        exp = SI_prefixes[str[-1]]
        return float(str[:-1]) * 10**exp
    except KeyError:
        return float(str)

?

</F>






More information about the Python-list mailing list