I have a string like a = 'This is an example string that has a code !3377! this is the code I want to extract'
.
How can I extract 3377
from this string, i.e., the part surrounded by !
?
I have a string like a = 'This is an example string that has a code !3377! this is the code I want to extract'
.
How can I extract 3377
from this string, i.e., the part surrounded by !
?
There are multiple ways of doing what you are looking for. But the most optimal way of doing it would be by using regular expressions.
For example, in the case you gave:
import re
def subtract_code_from(sentence: str) -> str:
m = re.search(r'\w?!(\d+)!\w?', sentence)
return m.group(0)
Keep in mind that what I've done is a very quick and loose solution I implemented in five minutes. I don't know what other types of particular cases you could encounter for each sentence. So it is your job to implement the proper regex to match all the cases.
I encourage you to follow this tutorial. And you can use this website to build your regexes.
Good luck.