Home > database >  FInding position of number in string
FInding position of number in string

Time:03-20

I would i like separate the letters from the numbers like this

inp= "AE123"
p= #position of where the number start in this case "2"

I've already tried to use str.find() but its has a limit of 3

CodePudding user response:

Extracting the letters and the digits

If the goal is to extract both the letters and the digits, regular expressions can solve the problem directly without need for indices or slices:

>>> re.match(r'([A-Za-z] )(\d )', inp).groups()
('AE', '123')

Finding the position of the number

If needed, regular expressions can also locate the indices for the match.

>>> import re
>>> inp = "AE123"
>>> mo = re.search(r'\d ', inp)
>>> mo.span()
(2, 5)
>>> inp[2 : 5]
'123'

CodePudding user response:

You can run a loop that checks for digits:

for p, c in enumerate(inp):
    if c.isdigit():
        break

print(p)

Find out more about str.isdigit

CodePudding user response:

this should work

for i in range(len(inp)):
    if inp[i].isdigit():
        p = i
        break

CodePudding user response:

#Assuming all characters come before the first numeral as mentioned in the question
def findWhereNoStart(string):
   start_index=-1
   for char in string:
        start_index =1
        if char.isdigit():
             return string[start_index:]
   return "NO NUMERALS IN THE GIVEN STRING"    
   
   
#TEST
print(findWhereNoStart("ASDFG"))
print(findWhereNoStart("ASDFG13213"))
print(findWhereNoStart("ASDFG1"))

#OUTPUT
"""
NO NUMERALS IN THE GIVEN STRING
13213
1
"""
        
  • Related