1

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.

1
  • 4
    Regex is an option: import re; re.findall(r"SN_(\d+)", fave_phrase) Commented Oct 4, 2022 at 12:29

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.