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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

10 lines
Python 3.9+
import 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

stdout
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

  1. Using a list comprehension with `str.isdigit()`: `''.join(c for c in text if c.isdigit())`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.