开发者

how to make a variable change from the text "1m" into "1000000" in python

I have variables with values like 1.7m 1.8k and 1.2b how can I convert them to a real number value for example

1.7m = 170开发者_如何学运维0000
1.8k = 1800
1.2b = 1200000000


I would define a dictionary:

tens = dict(k=10e3, m=10e6, b=10e9)

then

x='1.7m'
factor, exp = x[0:-1], x[-1].lower()
ans = int(float(factor) * tens[exp])


You might be interested in a units library like quantities or unum.


Using lambda:

>>> tens = {'k': 10e3, 'm': 10e6, 'b': 10e9}
>>> f = lambda x: int(float(x[:-1])*tens[x[-1]])
>>> f('1.7m')
17000000
>>> f('1.8k')
18000
>>> f('1.2b')
12000000000


Here is an example using re:

input = '17k, 14.05m, 1.235b'

multipliers = { 'k': 1e3,
                'm': 1e6,
                'b': 1e9,
              }

pattern = r'([0-9.]+)([bkm])'

for number, suffix in re.findall(pattern, input):
    number = float(number)
    print number * multipliers[suffix]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜