This post will discuss how to remove specific characters from a string in Python.

Since strings are immutable in Python, you cannot simply remove characters from it. However, you can create a copy of a string without specific characters. This post provides an overview of several functions to accomplish this.

1. Using str.translate() function

An efficient solution is to use the str.translate() function to remove certain characters from a string. It maps each character of the string through a translation table, which can be created using the str.maketrans() function.

Download  Run Code

 
If you have a list of characters, you can use the following code:

Download  Run Code

 
You can also specify a dictionary to str.maketrans() function. Following is a simple example demonstrating the mapping variant of str.translate():

Download  Run Code

2. Using Set

Another option is to filter the string to remove characters that match with the given list of characters.

Download  Run Code

 
Here’s a generator version of the above code:

Download  Run Code

3. Using Regex

Another plausible way is to use regular expressions for removing certain characters from a string. This can be done using the re.sub() function. All characters enclosed within the square brackets constitute a character class, which will be replaced with the second parameter to re.sub(), i.e., an empty string.

Download  Run Code

 
If you want to remove all characters present in a literal string, you can use it below. It uses the re.escape() function to escape characters having a special meaning in a regular expression.

Download  Run Code

 
If you have a list of characters that need to be removed from the string, you can do like:

Download  Run Code

That’s all about removing specific characters from a string in Python.

 
Also See:

Remove non-alphanumeric characters from a Python string