Delete a Character from a String in Python Example


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!

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap