Python – How to Extract all the digits from a String

PythonServer Side ProgrammingProgramming

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

Example

Below is a demonstration of the same −

my_string = "python is 12 fun 2 learn"

print("The string is : ")
print(my_string)

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

print("The numbers list is :")
print(my_result)

Output

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

Explanation

• 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.

Published on 08-Sep-2021 10:44:39