Home » Python » Remove All Occurrences of a Character in String Python

Remove All Occurrences of a Character in String Python

To remove all occurrences of a character in a string using Python, use the str.replace() method.

str.replace() method in Python replaces the specified phrase in the string with the new phrase. You can use the replace() method to remove all instances of a character. For example, replacing all instances of character ‘a’ with ‘c’

In this example, we will discuss how to use the str.replace() method in Python to remove all occurrences of a character in a string.

Use str.replace() to remove all occurrences of a character in a String

To replace all occurrences of a character in a string with a new character:

  1. Call the str.replace() method on the string and pass a character to search for a replacement and a new character.
  2. The replace() method returns a copy of a string in which all occurrences of a character are replaced by a new character.
str = "Delete all occurrences of a character in a String"

str1 = str.replace('a','')
print(str1)

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

  1. character ‘a’ to search for in the string for replacement.
  2. replacement character ”. It will replace all occurrences of ‘a’ with ”

It will return the copy of the string and store it in the str1 variable and print it using the print() in Python.

The output of the above program after removing all occurrences of a character in a string is:

Delete ll occurrences of  chrcter in  String

Cool Tip: How to remove a character from a list of strings in Python!

Conclusion

I hope the above article on how to remove all occurrences of a character in a string using the Python str.replace() method is helpful to you.

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

Leave a Comment