Python Forum

Full Version: number plus suffix
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i want to convert a number that has a suffix following the digits. i think i will need to split it at the point where the digits end and the suffix begins. the tool to convert ints in C (strtol) can also yield a pointer to where the digits end. int() in Python does not do that and will even fail the conversion if any non-digits follow the digits. i want to convert strings like '5m' and extract the suffix to work with that. 'm' can mean minutes, and with a map having 'm':60 multiply the 5 to get 300. i'd like to also support other bases like int(digits,0) does, as long as the suffix characters are not the same as any digits in that base (like not using 'd' as a suffix for hexadecimal). any suggestions? this is one of the things i need to limit to what is in the Python library itself.
It seems that regular expressions are the appropriate tool
>>> import re
>>> re.match(r"^(\d+)(.*)$", "5m").groups()
('5', 'm')
itertools module comes in mind, specifically dropwhile and groupby

>>> from itertools import dropwhile
>>> t = '5hours'
>>> ''.join([char for char in dropwhile(lambda char: char.isdigit(), t)])   # add .strip() if there is space between numbers and letters
hours
>>> from itertools import groupby
>>> t = '5hours'
>>> [''.join(group) for status, group in groupby(t, lambda char: char.isalpha()) if status == True][0]
hours
i'd like to solve the general case, like if my function was processing digits one at a time and stopping when something is not a valid digit which might need to be determined in context, such as convert a number and return a 2-tuple with the value and what cannot be processed. but the number's base may not be known in advance.
I posted a snippet for a python version of strtol here.
i was hoping there was a way to avoid parsing individual digits in Python, but it looks to be the only way to do it for this need. thanks for the link.