How to Remove a List of Characters from a String in Python?

Estimated read time 1 min read

To remove a list of characters from a string in Python, you can use the str.translate() method. Here’s an example:

# Remove a list of characters from a string
my_string = "Hello, World!"
chars_to_remove = ["o", "l"]
new_string = my_string.translate(str.maketrans("", "", "".join(chars_to_remove)))
print(new_string)  # Output: He, Wrld!

In this example, we define a string my_string and a list of characters to remove chars_to_remove. We create a new string new_string that contains all the characters of my_string except for the characters in chars_to_remove.

To do this, we use the str.maketrans() method to create a translation table that maps each character in chars_to_remove to the null string "". We then pass this translation table to the str.translate() method to remove the characters from the string.

Note that the str.translate() method is a powerful tool for manipulating strings in Python. You can use it to perform a wide variety of string operations, including removing characters, replacing characters, and more.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply