Remove Special Characters, Punctuation and Spaces from a String in Python



It is necessary to clean up the strings by removing the unwanted elements such as special characters, punctuation, and spaces. These unwanted characters can be involved in the tasks and cause unexpected results.

In this article, we are going to learn more about removing all special characters, punctuation and spaces from a string.

Using Python re Module

Through the re module, Python provides support for regular expressions. This module contains methods and classes that we can search, match, and modify a string (text content) using regular expressions.

ThePython re.sub() method accepts a pattern, a replacement string, and a string as parameters and replaces the occurrences of the pattern with the given replacement string. To remove all the special characters in a text using this method, you just need to provide the desired character as the replacement string.

Example

In the following example, we are going to consider the pattern [^A-Za-z0-9] along with the re.sub() method and observe the output.

import re
str1 = "Welcome #@ !! to Tutorialspoint123"
print(re.sub('[^A-Za-z0-9]+', '', str1))

The output of the above program is as follows -

WelcometoTutorialspoint123

Using Python str.isalnum() Method

In this approach, we are going to use the Python str.isalnum() method, which is used to check whether the string consists of alphanumeric characters. Here it returns true if the character is either a letter or a digit, and we also use the List comprehension to filter the characters and join them back by using the join() method.

Syntax

Following is the syntax for Python str.isalnum() method -

str.isalnum()

Example

Following is the example where we are going to consider the input string and apply the str.isalnum() method along with the list comprehension.

str1 = "Welcome #@ !! to Tutorialspoint2025"
result = ''.join([char for char in str1 if char.isalnum()])
print(result)

The following is the output of the above program -

WelcometoTutorialspoint2025

Using Python filter() Function

The third approach is by using the Python filter() function. It is used to filter out the elements from an iterable object based on the specified condition. In this scenario, it returns all the elements for which the function returns true.

Syntax

Following is the syntax for the Python filter() function -

filter(function, iterable)

Example

Consider the following example, where we are going to apply the filter() along with the str.isalnum().

str1 = "Welcome #@ !! to 20@@25"
result = ''.join(filter(str.isalnum, str1))
print(result)

The following is the output of the above program -

Welcometo2025
Updated on: 2025-05-02T20:34:26+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements