I have a string like
\"xdtwkeltjwlkejt7wthwk89lk\"
how can I get the index of the first digit in the string?
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}
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.