Remove Special Characters From a String in Python
This tutorial will cover the different ways of removing special characters from a string in Python.
Remove Special Characters from a String Using the str.isalnum() Method
The str.isalnum()
method returns True if the character supplied is alphanumeric. Knowing that we can build a new string without special characters like this:
string = 'Hello#- World!'
new_string = ''.join(char for char in string if char.isalnum())
print(new_string)
HelloWorld
In the above example, we iterate over the string with a for loop and return the character if it is alphanumeric before adding it to a new string using the .join()
method.
Remove Special Characters from a String Using re.sub() Method
The re.sub()
function can remove special characters from a when using regex grouping like this:
import re
string = 'Hello#- World!'
new_string = re.sub(r"[^a-zA-Z0-9]","",string)
print(new_string)
HelloWorld