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.
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.
\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.
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:
Now only ASCII digits survive.
Wrap the Logic in a Function
For repeated use, a helper function keeps the behavior explicit.
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:
- strip formatting characters
- validate the resulting digit string
- 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 outside0through9. 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 withstr.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
- Remove duplicate dict in list in Python
- Remove empty strings from a list of strings
- Remove empty strings from a list of strings
- Remove item from list based on condition
- Remove Item in Dictionary based on Value
- Remove items from one list in another
- Remove Last Two Characters in a String
- remove None value from a list without removing the 0 value
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.