Find the index of the first digit in a string

前端 未结 14 736
清酒与你
清酒与你 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:46

    To get all indexes do:

    idxs = [i for i in range(0, len(string)) if string[i].isdigit()]
    

    Then to get the first index do:

    if len(idxs):
        print(idxs[0])
    else:
        print('No digits exist')
    
    0 讨论(0)
  • 2020-12-28 12:47

    you can use regular expression

    import re
    y = "xdtwkeltjwlkejt7wthwk89lk"
    
    s = re.search("\d",y).start()
    
    0 讨论(0)
  • 2020-12-28 12:48

    I'm sure there are multiple solutions, but using regular expressions you can do this:

    >>> import re
    >>> match = re.search("\d", "xdtwkeltjwlkejt7wthwk89lk")
    >>> match.start(0)
    15
    
    0 讨论(0)
  • 2020-12-28 12:51

    Use re.search():

    >>> import re
    >>> s1 = "thishasadigit4here"
    >>> m = re.search(r"\d", s1)
    >>> if m:
    ...     print("Digit found at position", m.start())
    ... else:
    ...     print("No digit in that string")
    ... 
    Digit found at position 13
    
    0 讨论(0)
  • 2020-12-28 12:51

    As the other solutions say, to find the index of the first digit in the string we can use regular expressions:

    >>> s = 'xdtwkeltjwlkejt7wthwk89lk'
    >>> match = re.search(r'\d', s)
    >>> print match.start() if match else 'No digits found'
    15
    >>> s[15] # To show correctness
    '7'
    

    While simple, a regular expression match is going to be overkill for super-long strings. A more efficient way is to iterate through the string like this:

    >>> for i, c in enumerate(s):
    ...     if c.isdigit():
    ...         print i
    ...         break
    ... 
    15
    

    In case we wanted to extend the question to finding the first integer (not digit) and what it was:

    >>> s = 'xdtwkeltjwlkejt711wthwk89lk'
    >>> for i, c in enumerate(s):
    ...     if c.isdigit():
    ...         start = i
    ...         while i < len(s) and s[i].isdigit():
    ...             i += 1
    ...         print 'Integer %d found at position %d' % (int(s[start:i]), start)
    ...         break
    ... 
    Integer 711 found at position 15
    
    0 讨论(0)
  • 2020-12-28 12:52
    def first_digit_index(iterable):
        try:
            return next(i for i, d in enumerate(iterable) if d.isdigit())
        except StopIteration:
            return -1
    

    This does not use regex and will stop iterating as soon as the first digit is found.

    0 讨论(0)
提交回复
热议问题