Python – How to Extract all the digits from a String

When it is required to extract strings with a digit, a list comprehension and ‘isdigit’ method is used.


Below is a demonstration of the same −

my_string = "python is 12 fun 2 learn"

print("The string is : ")

my_result = [int(i) for i in my_string.split() if i.isdigit()]

print("The numbers list is :")


The string is :
python is 12 fun 2 learn
The numbers list is :
[12, 2]


  • A string is defined and is displayed on the console.

  • A list comprehension is used to iterate over the string, and every element is checked to see if it is a digit using the ‘isdigit’ function and is converted to an integer.

  • These are stored in a list and assigned to a variable.

  • This is the output that is displayed on the console.