Home > Software engineering >  Python get number sequence from a string with a index
Python get number sequence from a string with a index

Time:10-05

I want to get a number sequence from a string.

So I have string(folder_name) => "FGH SN_234256 aalhflsh"

with .find() I can find out where to start.

     search_fave_phrase = fave_phrase.find("SN_")

     print(search_fave_phrase)
     #Output 4

Now I want the whole number after the SN_. But if there is a whitespace or letter the number should stop. My goal is to get that number, no matter where it is in the string.

CodePudding user response:

Use regex:

import re

text = "FGH SN_234256 aalhflsh"

pattern = r'SN_([0-9] )'

print(re.findall(pattern=pattern, string=text)[0]) # (It's still a string so you might need to convert to int)

CodePudding user response:

I would use a regular expression.

import re

fave_phrase = "FGH SN_234256 aalhflsh"
match = re.search("SN_([0-9] )", fave_phrase)
print(match.group(1))

Explanation: It looks for "SN_" followed by numbers. group(0) would be "SN_234256" and group(1) is the part in brackets, i.e. "234256".

  • Related