So say that I have a string which is something along the lines of "One2three4". Is it possible for me to look through the string and take the integers and put them in their own string, so my final result will be "24". Thanks
Asked
Active
Viewed 78 times
1 Answers
6
Using str.join()
and str.isdigit()
:
>>> s = "One2three4"
>>> ''.join(c for c in s if c.isdigit())
'24'
This method looks through the string once and checks if each character is a digit or not; the characters that satisfy this are joined into a new string. In complexity terms, this is O(n), and as we need to check every character in the string, this is the best we can do.

CDJB
- 14,043
- 5
- 29
- 55