How to remove characters except digits from string in Python?

While working with texts in Python, we often encounter strings containing a mix of characters such as letters, digits, and whitespace. In some scenarios, we may need to extract only the numeric digits from such strings. Python provides several effective approaches to accomplish this task.

Using str.isdigit() with List Comprehension

The isdigit() method checks whether a character is a digit. Combined with list comprehension, it provides an elegant solution to filter out non-digit characters.

Syntax

str.isdigit()

Example

Here's how to remove all characters except digits using list comprehension and str.isdigit()

text = "Tuto1rials24Point35"
result = ''.join([char for char in text if char.isdigit()])
print(result)
12435

Using filter() Function

The filter() function creates an iterator from elements that satisfy a condition. We can use it with str.isdigit to filter only digit characters.

Syntax

filter(function, iterable)

Example

This example demonstrates filtering out non-digit characters using filter()

text = "Employment Id : 1A3D4Y6"
result = ''.join(filter(str.isdigit, text))
print(result)
1346

Using Regular Expressions

The re module provides powerful pattern matching capabilities. The pattern \D matches any non-digit character, which we can replace with an empty string using re.sub().

Example

Here's how to use regular expressions to remove all non-digit characters −

import re

text = "246T82P"
result = re.sub(r'\D', '', text)
print(result)
24682

Performance Comparison

Method Readability Performance Best For
List Comprehension High Good Simple filtering tasks
filter() Medium Good Functional programming style
Regular Expressions Medium Best for complex patterns Complex string manipulations

Conclusion

All three methods effectively remove non-digit characters from strings. Use list comprehension for simple, readable code, filter() for functional programming approaches, and regular expressions for complex pattern matching requirements.

Updated on: 2026-03-24T16:44:03+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements