Python Forum
number plus suffix - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: number plus suffix (/thread-18831.html)



number plus suffix - Skaperen - Jun-03-2019

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.


RE: number plus suffix - Gribouillis - Jun-03-2019

It seems that regular expressions are the appropriate tool
>>> import re
>>> re.match(r"^(\d+)(.*)$", "5m").groups()
('5', 'm')



RE: number plus suffix - perfringo - Jun-03-2019

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



RE: number plus suffix - Skaperen - Jun-03-2019

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.


RE: number plus suffix - Gribouillis - Jun-05-2019

I posted a snippet for a python version of strtol here.


RE: number plus suffix - Skaperen - Jun-05-2019

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.