Python - How To Remove Special Characters From the String in Python

ID : 113

viewed : 214

Tags : PythonPython String

vote vote

97

In this tutorial, we will discuss various ways to remove all the special characters from the string in Python. We can remove the special characters from the string by using functions or regular expressions.

Remove Special Characters From the String in Python Using the str.isalnum() Method

The str.isalnum() method returns True if the characters are alphanumeric characters, meaning no special characters in the string. It will return False if there are any special characters in the string.

In order to remove the special characters from the string, we will have to check if a character is alphanumeric and drop it otherwise. The example implementation of this method is below:

string = "Hey! What's up bro?"  new_string = ''.join(char for char in string if char.isalnum()) print(new_string) 

Output:

HeyWhatsupbro 

Remove Special Characters From the String in Python Using filter(str.isalnum, string) Method

To remove special characters from the string, we can also use filter(str.isalnum, string) method, similar to the method explained above. But in this approach, instead of using the for loop and if statement on str.isalnum() method, we will use filter() function.

Example code:

string = "Hey! What's up bro?"  new_string = ''.join(filter(str.isalnum, string))  print(new_string) 
HeyWhatsupbro 

Remove Special Characters From the String in Python Using Regular Expression

To remove the special character from the string, we could write a regular expression that will automatically remove the special characters from the string. The regular expression for this will be [^a-zA-Z0-9], where ^ represents any character except the characters in the brackets, and a-zA-Z0-9 represents that string can only have small and capital alphabets and numerical digits.

Example code:

import re  string = "Hey! What's up bro?" new_string = re.sub(r"[^a-zA-Z0-9]","",string) print(new_string) 

Output:

HeyWhatsupbro 

  • Related HOW TO?