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 = 1700000 1.8k = 1800 1.2b = 1200000000
Solution 1:
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])
Solution 2:
Solution 3:
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]
Solution 4:
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
Post a Comment for "How To Make A Variable Change From The Text "1m" Into "1000000" In Python"