Python - Parse a string with custom price units
What is fastest way to parse a string to int in Python? The string m开发者_开发问答ay include custom units, such as "k" (kilo), "m" (million), or "b" (billion).
For example:
100 -> 100
100k -> 100000
100m -> 100000000
100b -> 100000000000
Thanks.
def convert(val):
lookup = {'k': 1000, 'm': 1000000, 'b': 1000000000}
unit = val[-1]
try:
number = int(val[:-1])
except ValueError:
# do something
if unit in lookup:
return lookup[unit] * number
return int(val)
>>> print convert("100m")
>>> 100000000
Create a lookup table and then split the number into the number portion and the unit. If the unit portion exists, look to our table and use it to create the final number. Otherwise, return the number.
def numerize(s):
multipliers = {'k': 10**3, 'm': 10**6, 'b': 10**9}
if s[-1] in multipliers:
return int(s[:-1]) * multipliers[s[-1]]
else:
return int(s)
EDIT: better exemplification, possible-error fix
>>> def get_unit(ustr):
... if ustr == '': return 'u'
... return ustr.lower()
...
>>> import re
>>> r=re.compile('([1-9][0-9]*)([kKmMbBgG]?)')
>>> units={'k':1000,'m':1000000,'g':1000000000,'b':1000000000,'u':1}
>>> result=r.match('120k')
>>> int(result.group(1))*units[get_unit(result.group(2))]
120000
>>> result=r.match('44')
>>> int(result.group(1))*units[get_unit(result.group(2))]
44
>>> result=r.match('44M')
>>> int(result.group(1))*units[get_unit(result.group(2))]
44000000
>>>
You can define a dictionary that maps numbers to themselves and units to zeros:
units = {"0":"0", "1":"1", #etc.
"k":"000",
"m":"000000"} # etc.
Then you convert a string to an int like this
int_value = int("".join(map(units.get, string_value)))
精彩评论