How to Remove All Occurrences of a Character from a String in Python?

Estimated read time 2 min read

You can remove all occurrences of a character from a string in Python using the replace() method or a simple loop.

Using replace():

string = "this is a string with many characters"
char_to_remove = "i"

# Remove all occurrences of the character
new_string = string.replace(char_to_remove, "")

print(new_string)  # Output: "ths s a strng wth many charscters"

In this example, we have a string variable string and a character variable char_to_remove. We then use the replace() method to replace all occurrences of the character with an empty string. The resulting string will be "ths s a strng wth many charscters", with all the occurrences of the character “i” removed.

Using a loop:

string = "this is a string with many characters"
char_to_remove = "i"

# Remove all occurrences of the character
new_string = ""
for char in string:
    if char != char_to_remove:
        new_string += char

print(new_string)  # Output: "ths s a strng wth many charscters"

In this example, we have a string variable string and a character variable char_to_remove. We then use a loop to iterate over each character in the string and add all characters that are not equal to the character we want to remove to a new string. The resulting string will be "ths s a strng wth many charscters", with all the occurrences of the character “i” removed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply