How to Extract Digits Only from a String in Python
This code uses a regular expression to remove all non-digit characters from a mixed string, returning only the digits.
Python code
10 linesimport re
def extract_digits(text):
"""Return only the digits from the given text as a string."""
return re.sub(r'\D', '', text)
if __name__ == "__main__":
mixed = "abc123def456!@#789"
result = extract_digits(mixed)
print(result)
Output
123456789
How it works
The re.sub function scans the input string and replaces every match of the pattern \D (which matches any non-digit character) with an empty string. This effectively deletes all characters that are not digits. The result is a new string containing only the digit characters, preserving their original order. The function is pure and side-effect free, making it easy to reuse and test.
Common mistakes
- Using `\d+` with `re.findall` and then joining, which is less direct and may miss individual digits if separated
- Forgetting to handle non-string inputs, which would cause `TypeError`
Variations
- Using a list comprehension with `str.isdigit()`: `''.join(c for c in text if c.isdigit())`
- Using `re.findall(r'\d', text)` and joining the list
Real-world use cases
- Cleaning phone numbers from user input that contains hyphens, spaces, or letters.
- Extracting numeric IDs from log lines that mix text and digits.
- Parsing order numbers or transaction references from imported data streams.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.