You could use regular expressions to do this.
There is a very similar question here: Looping through python regex matches
You would just need a slightly different reg expression than the one in the answer from above.
A regex string: ([0-9]+)
would give you the answer you want.
Examining the regex above:
- The parenthesis
()
are for capturing a group, this is the a piece of the input that you want as an output.
- The square brackets
[]
is a regex class.
- The
0-9
means any number between 0 and 9.
- The
+
after the []
means 1 or more class matches.
So in this case [0-9]
means match any single digit number. [0-9]+
match any number, and any digit after that.
You can test your regular expressions on this website: https://regex101.com/
Just give me the code:
import re;
s = "I am 52 years old. The 48a24 is an example"
pattern = re.compile(r'([0-9]+)');
for group in re.findall(pattern, s):
print(group)
Gives output:
52
48
24