简体   繁体   English

将带有工程师前缀的字符串转换为float

[英]Convert string with engineer prefix to float

I have a string like '102.3k' I would like to convert this string with an engineer prefix notation to a float number. 我有一个类似'102.3k'的字符串,我想将此字符串与工程师前缀表示法转换为浮点数。

http://en.wikipedia.org/wiki/Engineering_notation http://en.wikipedia.org/wiki/Engineering_notation

Allowed prefixes are 允许的前缀是

posPrefixes = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
negPrefixes = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y']

k means 10^3 k表示10 ^ 3

M means 10^6 M表示10 ^ 6

m means 10^-3 m表示10 ^ -3

µ means 10^-6 µ表示10 ^ -6

I think I should use regex to do this but I have very few experience with regex. 我认为我应该使用正则表达式来执行此操作,但是我对正则表达式的经验很少。

edit: ideally the solution should also be able to convert any string so '102.3' (without prefix) should also be converted to float 编辑:理想情况下,解决方案还应该能够转换任何字符串,因此“ 102.3”(无前缀)也应该转换为浮点型

Try this out, no regex needed: 试试看,不需要正则表达式:

pos_postfixes = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
neg_postfixes = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y']

num_postfix = n[-1]
if num_postfix in pos_postfixes:
    num = float(n[:-1])
    num*=10**((pos_postfixes.index(num_postfix)+1)*3)
elif num_postfix in neg_postfixes:
    num = float(n[:-1])
    num*=10**(-(neg_postfixes.index(num_postfix)+1)*3)
else:
    num = float(n)
print(num)

Another thing to note is that in python, it is more common to use underscore variable names than camelcasing, see the pep-8: http://www.python.org/dev/peps/pep-0008/ 要注意的另一件事是,在python中,使用下划线变量名比使用驼峰更常见,请参见pep-8: http ://www.python.org/dev/peps/pep-0008/

If you want to control the value, you could try this: 如果要控制值,可以尝试以下操作:

import decimal
posPrefixes = {'k':'10E3', 'M':'10E6', 'G':'10E9', 'T':'10E12', 'P':'10E15', 'E':'10E18', 'Z':'10E21', 'Y':'10E24'}
negPrefixes = {'m':'10E-3', '?':'10E-6', 'n':'10E-9', 'p':'10E-12', 'f':'10E-15', 'a':'10E-18', 'z':'10E-21', 'y':'10E-24'}
val='102.3k'
if val[-1] in posPrefixes.keys():
    v = decimal.Decimal(val[:-1])
    print v*decimal.Decimal(posPrefixes[val[-1]])

val ='102.3n'
if val[-1] in negPrefixes.keys():
    v = decimal.Decimal(val[:-1])
    print v*decimal.Decimal(negPrefixes[val[-1]])

Output: 输出:

1.0230E+6 1.0230E + 6

1.023e-06 1.023e-06

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM