Python
String Manipulation
Data Cleaning
Regular Expressions
Programming

Remove characters except digits from string using Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you want to keep only digits from a Python string, the most common answers are re.sub and a character filter using str.isdigit(). The better choice depends on whether you want the shortest regex solution or the clearest built-in string logic.

Regex with re.sub

A direct regular-expression solution removes every non-digit character.

python
1import re
2
3text = "Invoice #A-1029"
4digits = re.sub(r"\D", "", text)
5print(digits)

\D means "any character that is not a digit," so replacing it with an empty string leaves only digits behind.

This is concise and common, especially in data-cleaning scripts.

str.isdigit() Without Regex

If you prefer to avoid regex for a simple task, filtering characters is equally valid.

python
text = "Invoice #A-1029"
digits = "".join(ch for ch in text if ch.isdigit())
print(digits)

This is often easier to read for developers who do not want a regular expression for such a small transformation.

ASCII Digits Versus Unicode Digits

One subtle detail is that str.isdigit() recognizes more than just ASCII 0 through 9. That can be useful or surprising depending on the data source.

If you want strictly ASCII digits, use a narrower check:

python
text = "Order 123 and 456"
digits = "".join(ch for ch in text if "0" <= ch <= "9")
print(digits)

Now only ASCII digits survive.

Wrap the Logic in a Function

For repeated use, a helper function keeps the behavior explicit.

python
1import re
2
3
4def extract_digits(text: str) -> str:
5    return re.sub(r"\D", "", text)
6
7
8print(extract_digits("Phone: +1 (555) 123-4567"))

That also makes it easier to swap the internal strategy later if the definition of digit changes.

When This Is Not Enough

Removing non-digits is usually a cleanup step, not full validation. A cleaned phone number may still be too short. A cleaned identifier may still have a bad checksum. A cleaned money string may have lost decimal information that should not have been discarded.

So the real workflow is often:

  1. strip formatting characters
  2. validate the resulting digit string
  3. parse or store it

Keeping those stages separate produces clearer code and fewer hidden assumptions.

Performance Notes

For ordinary strings, both regex and filtering are fine. The bigger question is readability. Regex is compact, while isdigit() makes the condition more explicit. In most application code, the maintenance difference matters more than micro-benchmark differences.

If you are processing extremely large volumes of text, benchmark the exact operation in context instead of assuming one form is always faster.

Common Pitfalls

  • Treating digit extraction as the same thing as validation leads to bad downstream assumptions. A string containing only digits may still be semantically invalid.
  • Using str.isdigit() when you really need ASCII digits can preserve characters outside 0 through 9. Use an explicit range if the format is strict.
  • Reaching for regex when the team finds a simple comprehension clearer can make the code less approachable. Pick the form that matches the codebase style.
  • Forgetting that an empty result is possible can cause later parsing failures. Check for the empty string before converting to int.
  • Removing all non-digits from values such as decimal numbers or signed values can destroy meaningful information. Confirm that digits-only output is really what the problem requires.

Summary

  • In Python, the standard solutions are re.sub(r"\\D", "", text) and filtering with str.isdigit().
  • Regex is compact, while character filtering is explicit and easy to read.
  • If you need only ASCII digits, use a stricter character-range check.
  • Digit extraction is usually a preprocessing step, not full validation.
  • Choose the approach that matches the input rules and the readability needs of the codebase.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.