Cleanest way to obtain the numeric prefix of a string

后端 未结 9 1382
醉话见心
醉话见心 2021-01-07 19:21

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

相关标签:
9条回答
  • 2021-01-07 19:55
    input = '123abc456def'
    output = re.findall(r'^\d+', input)
    

    Will return ['123'] too.

    0 讨论(0)
  • 2021-01-07 19:58

    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.

    0 讨论(0)
  • 2021-01-07 19:59

    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'
    
    0 讨论(0)
提交回复
热议问题