Find the index of the first digit in a string

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

提交回复
热议问题