string = "abc123" # Method 1 ''.join(char for char in string if char.isdigit()) #Method 2 import re re.sub("[^0-9]", "", string)
Here is what the above code is Doing:
1. The first line is using a list comprehension to iterate through the string and only keep the characters that are digits.
2. The second line is using the re module to replace all non-digit characters with an empty string.