Find the index of the first digit in a string

Solution 1:

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

Solution 2:

Here is a better and more flexible way, regex is overkill here.

s = 'xdtwkeltjwlkejt7wthwk89lk'

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

output:

15

To get all digits and their positions, a simple expression will do

>>> [(i, c) for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()]
[(15, '7'), (21, '8'), (22, '9')]

Or you can create a dict of digit and its last position

>>> {c: i for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()}
{'9': 22, '8': 21, '7': 15}

Solution 3:

Thought I'd toss my method on the pile. I'll do just about anything to avoid regex.

sequence = 'xdtwkeltjwlkejt7wthwk89lk'
i = [x.isdigit() for x in sequence].index(True)

To explain what's going on here:

  • [x.isdigit() for x in sequence] is going to translate the string into an array of booleans representing whether each character is a digit or not
  • [...].index(True) returns the first index value that True is found in.

Solution 4:

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]

Solution 5:

import re
first_digit = re.search('\d', 'xdtwkeltjwlkejt7wthwk89lk')
if first_digit:
    print(first_digit.start())