I have a string like
"xdtwkeltjwlkejt7wthwk89lk"
how can I get the index of the first digit in the string?
To get the index of the first number in a string, call the search() method passing it a regular expression that matches a digit. The search method returns the index of the first match of the regular expression in the string.
To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string.
Use the find() Function to Find First Occurrence in Python We can use the find() function in Python to find the first occurrence of a substring inside a string. The find() function takes the substring as an input parameter and returns the first starting index of the substring inside the main string.
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
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With