parsing engineering symbols

Bengt Richter bokr at oz.net
Wed Dec 21 15:41:58 CET 2005


On Tue, 20 Dec 2005 23:28:12 +0100, "Fredrik Lundh" <fredrik at pythonware.com> wrote:

>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)
>
>?

Nit: why not move 10** out of myfloat into SI_prefixes
     (i.e., just retrieve precalculated factors)?

Nit_2: No twinge of conscience shadowing str? ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list