Python strings – Remove specific characters from a string

In this post we will be creating a Python script that will remove specific characters from a string, to do this we will be using the ‘re’ module which provides regular expression matching operations similar to those found in Perl.

See the below string which contains the ‘!’, ‘#’, ‘$’ characters which we are wanting to remove.

string="He!llo# World$"

See the snippet of code below where we make use of the ‘sub()’ method to replace/remove the characters from out string.

import re

string="He!llo# World$"

string = re.sub('[!#$]', '', string)
print(string)

The above would return the following as output.

Hello World
>>> 

Leave a Reply