
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Characters Except Digits from String in Python
While working with the texts in Python, we will find the strings that contain a mix of characters such as letters, digits, and white-space. In some scenarios, we may need to extract only the numeric digits from such strings. For achieving this, Python provides various ways. Let's explore one by one -
Using Python str.isdigit() Method
The first approach is by using the Python isdigit() method. It is used to check whether the character is a digit. It returns true if all the characters in the input string are digits.
Syntax
Following is the syntax for Python str.isdigit() method -
str.isdigit()
Example
In the following example, we are going to remove all characters except digits using the list comprehension and str.isdigit() method.
str1 = "Tuto1rials24Point35" result = ''.join([char for char in str1 if char.isdigit()]) print(result)
The output of the above program is as follows -
12435
Using Python filter() Function
The Python filter() function is used to filter out the elements from an iterable object based on the specified condition. In this approach, we are going to apply the filter(str.isdigit) to return the iterator that includes only digit characters.
Syntax
Following is the syntax for the Python filter() function -
filter(function, iterable)
Example
Consider the following example, where we are going to filter out all the non-digit characters using the filter() function and str.isdigit().
str1 = "Employment Id : 1A3D4Y6" result = ''.join(filter(str.isdigit, str1)) print(result)
The following is the output of the above program -
1346
Using Python "re" Module
The third approach is by using the Python re module. The Python re module supports regular expressions, helping in string pattern matching and manipulation.
Here, we are going to use the regular expression '\D' pattern to match only the digit characters and also apply the re.sub(r'\D', '') for replacing all the non-digit characters with an empty string.
Example
Following is the example where we are going to use the regular expression to remove all the non-digit characters.
import re str1 = "246T82P" result = re.sub(r'\D', '', str1) print(result)
The output of the above program is as follows -
24682