If you have a String in Python and you want to delete a specific character from it, you can do that by using the replace() method.
Let's take a look at an example.
string = "This is so Cool!"
Let's say you want to delete the letter capital C
new_string = string.replace("C","")
print(new_string)
Output:
string = "This is so ool!"
Note, if the character is not unique, the replace method will replace all the occurrences here with blank and shift all other letters by one to the left.
There is a solution to this. You can add another optional parameter that can help you delete one or more occurrences.
So there is there character "o" in our example, let's look at an example with it.
new_string_remove_first_o = string.replace("o","",1)
new_string_remove_second_o = string.replace("o","",2)
new_string_remove_third_o = string.replace("o","",3)
print(new_string_remove_first_o)
print(new_string_remove_second_o)
print(new_string_remove_third_o)
Output:
This is s Cool!
This is s Col!
This is s Cl!
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!