Python | Deleting all occurrences of character

These days string manipulation is very popular in Python, and due to it’s immutable character, sometimes, it becomes more important to know it’s working and hacks. This particular article solves the problem of deleting all occurrences of character from a string. Let’s discuss ways in which this can be achieved.

Method #1 : Using translate()
Usually this function is used to convert a particular character to some other character. By translating the resultant removal character to “None”, this function can perform this task. This function works only for Python2

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate working of
# Deleting all occurrences of character
# Using translate()
  
# initializing string 
test_str = "GeeksforGeeks"
  
# initializing removal character
rem_char = "e"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# Using translate()
# Deleting all occurrences of character
res = test_str.translate(None, rem_char)
  
# printing result 
print("The string after character deletion : " + str(res))

chevron_right


Output :



The original string is : GeeksforGeeks
The string after character deletion : GksforGks

 

Method #2 : Using replace()
This function works functionally quite similar to the above function, but it is recommended due to several reasons. It can be used in newer versions of Python and is more efficient than the above function. We replace the empty string instead of None as above for using this function to perform this task.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Deleting all occurrences of character
# Using replace()
  
# initializing string 
test_str = "GeeksforGeeks"
  
# initializing removal character
rem_char = "e"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# Using replace()
# Deleting all occurrences of character
res = test_str.replace(rem_char, "")
  
# printing result 
print("The string after character deletion : " + str(res))

chevron_right


Output :

The original string is : GeeksforGeeks
The string after character deletion : GksforGks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.