Here we will see how to remove special characters from String in Python.

string package:

Python string package is a very good solution to remove the special characters from a string. In the following example, I have prepared a string having different special characters, lets see how we can remove them using python string package.

import string

if __name__ == '__main__':
    data = '#(Hello! I need to remove $pl @hars in Pyth@n)'
    cleaned_data = data.translate(str.maketrans('','',string.punctuation))
    print(cleaned_data)

Output:

Hello I need to remove pl hars in Pythn

The cstr.maketrans() is a static method returns a translation table that will map each character in from into the character at the same position in to; from and to must be bytes objects and have the same length.

string.punctuation is a pre-initialized string with a set of punctuations

re package:

We can remove the special characters using a python regular expression package. As string.punctuation has limited set of punctuations if your string has lot more type of special characters you can go with python regex.

import re
if __name__ == '__main__':
    data = '#(Hello! I need to remove $pl @hars in Pyth@n)'

    cleaned_data = re.sub('[^A-Za-z0-9 ]+', '', data)
    print(cleaned_data)

Output:

Hello I need to remove pl hars in Pythn

References:

Happy Learning 🙂