Find the index of the first digit in a string

前端 未结 14 734
清酒与你
清酒与你 2020-12-28 12:29

I have a string like

\"xdtwkeltjwlkejt7wthwk89lk\"

how can I get the index of the first digit in the string?

相关标签:
14条回答
  • 2020-12-28 12:32

    In Python 3.8+ you can use re.search to look for the first \d (for digit) character class like this:

    import re
    
    my_string = "xdtwkeltjwlkejt7wthwk89lk"
    
    if first_digit := re.search(r"\d", my_string):
        print(first_digit.start())
    
    0 讨论(0)
  • 2020-12-28 12:33
    instr = 'nkfnkjbvhbef0njhb h2konoon8ll'
    numidx = next((i for i, s in enumerate(instr) if s.isdigit()), None)
    print numidx
    

    output:

    12
    

    numidx will be the index of the first occurrence of a digit in instr. If there are no digits in instr, numidx will be None.

    I didn't see this solution here, and thought it should be.

    0 讨论(0)
  • 2020-12-28 12:34
    import re
    first_digit = re.search('\d', 'xdtwkeltjwlkejt7wthwk89lk')
    if first_digit:
        print(first_digit.start())
    
    0 讨论(0)
  • 2020-12-28 12:34

    Here is another regex-less way, more in a functional style. This one finds the position of the first occurrence of each digit that exists in the string, then chooses the lowest. A regex is probably going to be more efficient, especially for longer strings (this makes at least 10 full passes through the string and up to 20).

    haystack = "xdtwkeltjwlkejt7wthwk89lk"
    digits   = "012345689"
    found    = [haystack.index(dig) for dig in digits if dig in haystack]
    firstdig = min(found) if found else None
    
    0 讨论(0)
  • 2020-12-28 12:34
    import re
    result = "  Total files:...................     90"
    match = re.match(r".*[^\d](\d+)$", result)
    if match:
        print(match.group(1))
    

    will output

    90
    
    0 讨论(0)
  • 2020-12-28 12:37

    Seems like a good job for a parser:

    >>> from simpleparse.parser import Parser
    >>> s = 'xdtwkeltjwlkejt7wthwk89lk'
    >>> grammar = """
    ... integer := [0-9]+
    ... <alpha> := -integer+
    ... all     := (integer/alpha)+
    ... """
    >>> parser = Parser(grammar, 'all')
    >>> parser.parse(s)
    (1, [('integer', 15, 16, None), ('integer', 21, 23, None)], 25)
    >>> [ int(s[x[1]:x[2]]) for x in parser.parse(s)[1] ]
    [7, 89]
    
    0 讨论(0)
提交回复
热议问题