What is the cleanest way to obtain the numeric prefix of a string in Python?
By \"clean\" I mean simple, short, readable. I couldn\'t care less about performance, a
input = '123abc456def'
output = re.findall(r'^\d+', input)
Will return ['123']
too.
One way, but not very efficient since it works through the whole string without break
would be:
input_string = '123abc456def'
[input_string[:c] for c in range(len(input_string)) if input_string[:c].isdigit()][-1]
This appends each substring with increasing size if it is a digit and then appends it. So the last element is the one you look for. Because it is the longest startstring that is still a digit.
You can use itertools.takewhile which will iterate over your string (the iterable argument) until it encounters the first item which returns False
(by passing to predictor function):
>>> from itertools import takewhile
>>> input = '123abc456def'
>>> ''.join(takewhile(str.isdigit, input))
'123'