Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index of the first digit in a string

I have a string like

"xdtwkeltjwlkejt7wthwk89lk" 

how can I get the index of the first digit in the string?

like image 392
AP257 Avatar asked Dec 22 '10 15:12

AP257


People also ask

How do you find the index of the first number in a 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.

How do you get the first digit of a string in Python?

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.

How do you find the index of the first occurrence of a substring in a string in Python?

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.


2 Answers

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 
like image 194
bgporter Avatar answered Oct 14 '22 08:10

bgporter


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} 
like image 24
Anurag Uniyal Avatar answered Oct 14 '22 09:10

Anurag Uniyal