How to extract numbers from a string using Python?


To extract each digit from a string −

>>> str1='a34e 345 bcd 5he 78 xyz'
>>> for s in str1:
if s.isdigit():print (s)

3
4
3
4
5
5
7
8

To extract only integers from a string in which words are separated by space character −

>>> str1='h3110 23 cat 444.4 rabbit 11 2 dog'
>>> for s in str1.split():
if s.isdigit():
print ((s))

23
11
2

Updated on: 23-Jun-2020

406 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements