Cleanest way to obtain the numeric prefix of a string

后端 未结 9 1377
醉话见心
醉话见心 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:34

    Here is my way:

    output = input[:next((i for i,v in enumerate(input) if not v.isdigit()),None)]
    
    0 讨论(0)
  • 2021-01-07 19:39

    This is the simplest way to extract a list of numbers from a string:

    >>> import re
    >>> input = '123abc456def'
    >>> re.findall('\d+', s)
    ['123','456']
    

    If you need a list of int's then you might use the following code:

       >>> map(int, re.findall('\d+', input ))
       [123,456]
    

    And now you can access the first element [0] from the above list

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

    Another regexp version strips away everything starting with the first non-digit:

    import re
    output = re.sub('\D.*', '', input)
    
    0 讨论(0)
  • 2021-01-07 19:40
    input[:len(input) - len(input.lstrip("0123456789"))]
    
    0 讨论(0)
  • 2021-01-07 19:49

    You could use regex

    import re
    initialNumber = re.match(r'(?P<number>\d+)', yourInput).group('number')
    
    0 讨论(0)
  • 2021-01-07 19:52

    Simpler version (leaving the other answer as there's some interesting debate about which approach is better)

    input[:-len(input.lstrip("0123456789"))]
    
    0 讨论(0)
提交回复
热议问题