1

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

CDJB
  • 14,043
  • 5
  • 29
  • 55
Beanhead
  • 53
  • 7
  • 3
    Does this answer your question? [Extract Number from String in Python](https://stackoverflow.com/questions/26825729/extract-number-from-string-in-python) – Ocaso Protal Dec 13 '19 at 14:52

1 Answers1

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