Home » Python » Remove Multiple Characters from String in Python

Remove Multiple Characters from String in Python

To remove multiple characters from a string in Python, use the str.replace() method that accepts parameters old and new phrases like string to search for and new value for replacement.

str.replace() in Python replaces the specified phrase in the string with the new phrase. Use the replace() method to remove multiple characters from a string.

In this example, we will discuss how to use the str.replace() method in Python to remove multiple characters from a string and print the new string that excludes these characters.

Use str.replace() to remove multiple characters from a string in Python

To remove multiple characters from a string in Python:

  1. Create a string and copy the string to another variable.
  2. Create a string variable that contains multiple characters.
  3. Use for loop to iterate over multiple characters.
  4. Within the for loop, use replace() on a string to search multiple characters and replace it with ” and assign the result to the string.
my_string = "Hi! Welcome to Python Programming@"
multi_chars = "!@"

# Copy the original string to another variable
temp_string = my_string

for ch in multi_chars:
    temp_string = temp_string.replace(ch,"")
    
print(temp_string)

In the above Python program, we pass the following parameters to replace() :

  1. my_string variable stores the string.
  2. multi_chars variable stores the multiple characters which need to be excluded from the string.
  3. Copy the original string to another string variable as temp_string
  4. Use the for loop to iterate for multiple characters.
  5. Within the for loop, use replace() method over temp_string to search for a character and replace it with ”
  6. Assign the result back to temp_string so that in the next for loop iteration, it will use the updated string.

Use the the print() in Python to print the final string that excludes those multiple characters.

The output of the above program after removing multiple characters from a string is:

Hi Welcome to Python Programming

Cool Tip: How to remove new lines from a string in Python!

Conclusion

I hope the above article on how to remove multiple characters from a string in the Python using str.replace() method is helpful to you.

You can find more topics about the Python tutorials on the DataVisualizr Home page.

Leave a Comment