remove a character from a string in python

Using replace() method

The replace() method can be used to remove a character or a substring from a string by replacing it with an empty string.

main.py
string = "hello world"
char_to_remove = "l"
new_string = string.replace(char_to_remove, "")
print(new_string)   # output: "heo word"
133 chars
5 lines

Using split() and join() methods

The split() method can be used to split a string into a list of substrings based on a delimiter. We can use this method to split the string at the character we want to remove, and then join the list of substrings back into a string using the join() method.

main.py
string = "hello world"
char_to_remove = "l"
list_of_strings = string.split(char_to_remove)
new_string = "".join(list_of_strings)
print(new_string)   # output: "heo word"
170 chars
6 lines

Using slicing

Slicing can also be used to remove a character from a string by creating a new string that includes only the characters before and after the one we want to remove.

main.py
string = "hello world"
char_to_remove = "l"
index_of_char = string.index(char_to_remove)
new_string = string[:index_of_char] + string[index_of_char+1:]
print(new_string)   # output: "heo word"
193 chars
6 lines

Note: If the character is not found using index(), the program will throw a ValueError.

gistlibby LogSnag