How to remove a list of characters in string in Python?


In this article, we are going to find out how to remove a list of characters in string in Python.

The first approach is by using the replace() method. This method takes 2 parameters, the character we would like to replace and the character with which we are replacing. This method takes a string as input and we will get the modified string as output.

The replace string method creates a new string by replacing some of the characters in the given string with new ones. The initial string is unaffected and unchanged.

Example

In the example given below, we are taking a string as input and we are removing list of unwanted characters using the replace() method 

str1 = "Welcome to tutorialspoint"

print("The given string is")
print(str1)

print("Removing the character 't' from the input string")
print(str1.replace('t',''))

Output

The output of the above example is as follows −

The given string is
Welcome to tutorialspoint
Removing the character 't' from the input string
Welcome o uorialspoin

Using Regular Expressions

The second method involves the use of regular expressions. The technique re.sub is used in conjunction with a regular expression. We use re.sub() to delete the unnecessary characters and replace them with empty spaces.

Example

In the example given below, we are taking a string as input and we are removing a list of characters using Regular expressions

import re 
str1 = "Welcome to tutorialspoint"

print("The given string is")
print(str1)

print("The updated string is")
print(re.sub("e|t", " ",str1))

Output

The output of the above example is as follows −

The given string is
Welcome to tutorialspoint
The updated string is
W lcom o u orialspoin

Using join() and generator

The third technique is to use a generator's join() function. We create a list of unneeded characters, then iterate through the string to see if the character is in the list of undesirable characters. If it isn't, we use the join() function to add that specific character.

Example

In the example given below, we are taking a string as input and we are removing a list of characters using the join() method 

str1 = "Welcome to tutorialspoint"

print("The given string is")
print(str1)

remove = ['e','t']
str1 = ''.join(x for x in str1 if not x in remove)
print("The updated string is")
print(str1)

Output

The output of the above example is given below −

The given string is
Welcome to tutorialspoint
The updated string is
Wlcom o uorialspoin

Updated on: 07-Dec-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements