In areas like natural language processing, data science, and data mining, we need to process a huge amount of text data. For this, we normally use strings and lists in Python. Given a list of characters or a string, we sometimes need to remove one or all occurrences of a character from the list or string. In this article, we will discuss different ways to remove all the occurrences of a character from a list or a string in python.
- Remove an Element From a List Using the pop() Method
- Delete an Element From a List Using the remove() Method
- Remove All Occurrences of a Character From List
- Remove All Occurrences of a Character From a String in Python
- Delete All Occurrences of a Character From a String in Python Using for Loop
- Remove All Occurrences of a Character From a String in Python Using List Comprehension
- Delete All Occurrences of a Character From a String in Python Using the split() Method
- Remove All Occurrences of a Character From a String in Python Using the filter() Function
- Delete All Occurrences of a Character From a String in Python Using the replace() Method
- Remove All Occurrences of a Character From a String in Python Using the translate() Method
- Delete All Occurrences of a Character From a String in Python Using Regular Expressions
- Conclusion
Remove an Element From a List Using the pop() Method
Given a list, we can remove an element from the list using the pop()
method. The pop()
method, when invoked on a list removes the last element from the list. After execution, it returns the deleted element. You can observe this in the following example.
myList = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", myList)
x = myList.pop()
print("The popped element is:", x)
print("The modified list is:", myList)
Output:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The popped element is: 7
The modified list is: [1, 2, 3, 4, 5, 6]
In the above example, you can see that the last element of the list has been removed from the list after the execution of the pop()
method.
However, If the input list is empty, the program will run into IndexError
. It means that you are trying to pop an element from an empty list. For instance, look at the example below.
myList = []
print("The original list is:", myList)
x = myList.pop()
print("The popped element is:", x)
print("The modified list is:", myList)
Output:
The original list is: []
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
x = myList.pop()
IndexError: pop from empty list
You can observe that the program has run into an IndexError
exception with the message “IndexError: pop from empty list
“.
You can also remove the element from a specific index in the list using the pop()
method. For this, you will need to provide the index of the element.
The pop()
method, when invoked on a list, takes the index of the element that needs to be removed as its input argument. After execution, it removes the element from the given index. The pop()
method also returns the removed element. You can observe this in the following example.
myList = [1, 2, 3, 4, 5, 6, 7, 8]
print("The original list is:", myList)
x = myList.pop(3)
print("The popped element is:", x)
print("The modified list is:", myList)
Output:
The original list is: [1, 2, 3, 4, 5, 6, 7, 8]
The popped element is: 4
The modified list is: [1, 2, 3, 5, 6, 7, 8]
Here, We have popped out the element at index 3 of the list using the pop()
method.
Delete an Element From a List Using the remove() Method
If you don’t know the index of the element that has to be removed, you can use the remove()
method. The remove()
method, when invoked on a list, takes an element as its input argument. After execution, it removes the first occurrence of the input element from the list. The remove()
method doesn’t return any value. In other words, it returns None
.
You can observe this in the following example.
myList = [1, 2, 3, 4,3, 5,3, 6, 7, 8]
print("The original list is:", myList)
myList.remove(3)
print("The modified list is:", myList)
Output:
The original list is: [1, 2, 3, 4, 3, 5, 3, 6, 7, 8]
The modified list is: [1, 2, 4, 3, 5, 3, 6, 7, 8]
In the above example, you can see that the 1st occurrence of element 3 is removed from the list after the execution of the remove()
method.
If the value given in the input argument to the remove()
method doesn’t exist in the list, the program will run into a ValueError
exception as shown below.
myList = []
print("The original list is:", myList)
myList.remove(3)
print("The modified list is:", myList)
Output:
The original list is: []
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myList.remove(3)
ValueError: list.remove(x): x not in list
In the above example, the list is empty. Hence, the number 3 isn’t an element of the list. Therefore, when we invoke the remove()
method, the program runs into the ValueError
exception with the message “ValueError: list.remove(x): x not in list
“.
Till now, we have discussed how to remove an element from a list. Let us now discuss how we can remove all occurrences of a character in a list of characters in python.
Remove All Occurrences of a Character From List
Given a list of characters, we can remove all the occurrences of a value using a for loop and the append()
method. For this, we will use the following steps.
- First, we will create an empty list named
outputList
. For this, you can either use square brackets or thelist()
constructor. - After creating
outputList
, we will traverse through the input list of characters using a for loop. - While traversing the list elements, we will check if we need to remove the current character.
- If yes, we will move to the next character using the continue statement. Otherwise, we will append the current character to
outputList
using theappend()
method.
After execution of the for loop, we will get the output list of characters in outputList. In the outputList, all the characters except those that we need to remove from the original list will be present. You can observe this in the following python program.
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
outputList = []
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
for character in myList:
if character == charToDelete:
continue
outputList.append(character)
print("The modified list is:", outputList)
Output:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
Delete All Occurrences of a Character From a List Using List Comprehension
Instead of using the for loop, we can use list comprehension and the membership operator ‘in
’ to remove all the occurrences of a given character.
The in
operator is a binary operator that takes an element as its first operand and a container object like a list as its second operand. After execution, it returns True
if the element is present in the container object. Otherwise, it returns False
. You can observe this in the following example.
myList = [1, 2, 3, 4,3, 5,3, 6, 7, 8]
print("The list is:", myList)
print(3 in myList)
print(1117 in myList)
Output:
The list is: [1, 2, 3, 4, 3, 5, 3, 6, 7, 8]
True
False
Using list comprehension and the ‘in
’ operator, we can create a new list having all the characters except those that we need to remove from the original list as shown in the following example.
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
outputList = [character for character in myList if character != charToDelete]
print("The modified list is:", outputList)
Output:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
Remove All Occurrences of an Element From a List Using the remove() Method
Instead of creating a new list, we can also remove all the instances of a character from the original list. For this, we will use the remove()
method and the membership operator ‘in
’.
- To remove all the instances of a given element from the given list of characters, we will check if the character is present in the list using the ‘
in
’ operator. If yes, we will remove the character from the list using the remove method. - We will use a while loop to repeatedly check for the presence of the character to remove it from the list.
- After removing all the occurrences of the given character, the program will exit from the while loop.
In this way, we will get the output list by modifying the original list as shown below.
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
while charToDelete in myList:
myList.remove(charToDelete)
print("The modified list is:", myList)
Output:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
Delete All Occurrences of a Character Using the filter() Function
We can also use the filter()
function to remove all occurrences of a character from a list of characters.
The filter()
function takes another function say myFun
as its first input argument and a container object like a list as its second argument. Here, myFun
should take an element of the container object as its input argument. After execution, it should return either True
or False
.
If the output of myFun
is True
for any element of the container object given in input, the element is included in the output. Otherwise, the elements aren’t included in the output.
To remove all the occurrences of a given item in a list using the filter()
method, we will follow the following steps.
- First, we will define a function
myFun
that takes a character as an input argument. It returnsFalse
if the input character is equal to the character that we need to remove. Otherwise, it should returnTrue
. - After defining
myFun
, we will passmyFun
as the first argument and the list of characters as the second input argument to thefilter()
function. - After execution, the
filter()
function will return an iterable object containing the characters that aren’t removed from the list. - To convert the iterable object into a list, we will pass the iterable object to the
list()
constructor. In this way, we will get the list after removing all the occurrences of the specified character.
You can observe the entire process in the following example.
def myFun(character):
charToDelete = 'c'
return charToDelete != character
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
outputList=list(filter(myFun,myList))
print("The modified list is:", outputList)
Output:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
Instead of defining the function myFun
, we can create a lambda function and pass it to the filter function to remove all the instances of character from the list. You can do it as follows.
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
outputList = list(filter(lambda character: character != charToDelete, myList))
print("The modified list is:", outputList)
Output:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
Till now, we have discussed different methods to remove all the occurrences of a character in a list. Now we will discuss how we can remove occurrences of a specific character from a python string.
Remove All Occurrences of a Character From a String in Python
Given an input string, we can remove one or all occurrences of a character from a string using different string methods as well as a regular expression method. Let us discuss each of them one by one.
Delete All Occurrences of a Character From a String in Python Using for Loop
To remove all the occurrences of the particular character from a string using the for loop, we will follow the following steps.
- First, we will create an empty string named
outputString
to store the output string. - After that, we will iterate through the characters of the original string.
- While iterating over the characters of the string, if we find the character that we need to remove from the string, we will move to the next character using the continue statement.
- Otherwise, we will concatenate the current character to
outputString
.
After iterating till the last character of the string using the for loop using the above steps, we will get the output string in the new string named outputString
. You can observe that in the following code example.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
outputString = ""
for character in myStr:
if character == charToDelete:
continue
outputString += character
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
Remove All Occurrences of a Character From a String in Python Using List Comprehension
Instead of using the for loop, we can remove the occurrences of a specific value from a given string using the list comprehension and the join()
method.
- First, we will create a list of characters of the string that we don’t need to remove for the string using list comprehension as shown below.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = [character for character in myStr if character != charToDelete]
print("The list of characters is:")
print(myList)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list of characters is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
- After obtaining the list, we will use the
join()
method to create the output list. Thejoin()
method when invoked on a special character, takes an iterable object containing characters or strings as its input argument. After execution, it returns a string. The output string contains the characters of the input iterable object separated by the special character on which the join method is invoked. - We will use the empty character
“”
as the special character. We will invoke thejoin()
method on the empty character with the list obtained from the previous step as its input argument. After execution of thejoin()
method, we will get the desired output string. You can observe this in the following example.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = [character for character in myStr if character != charToDelete]
print("The list of characters is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list of characters is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
The modified string is: pythonforbeginners
Delete All Occurrences of a Character From a String in Python Using the split() Method
We can also use the split()
method to remove all the occurrences of a character from a given string. The split()
method, when invoked on a string, takes a separator as its input argument. After execution, it returns a list of substrings that are separated by the separator.
To remove all the occurrences of a given character from a given string, we will use the following steps.
- First, we will invoke the
split()
method on the original string. W will pass the character that has to be removed as the input argument to thesplit()
method. We will store the output of thesplit()
method inmyList
. - After obtaining
myList
, we will invoke thejoin()
method on an empty string withmyList
as the input argument to thejoin()
method. - After execution of the
join()
method, we will get the desired output. So, we will store it in a variableoutputString
.
You can observe the entire process in the following example.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = myStr.split(charToDelete)
print("The list is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
Output:
The character to delete: c
The list is:
['py', 't', 'honf', 'orbeg', 'inn', 'ers']
The modified string is: pythonforbeginners
Remove All Occurrences of a Character From a String in Python Using the filter() Function
We can also use the filter()
function with the join()
method and lambda function to remove the occurrences of a character from a string in Python.
The filter()
function takes another function say myFun
as its first input argument and an iterable object like a string as its second input argument. Here, myFun
should take the character of the string object as its input argument. After execution, it should return either True
or False
.
If the output of myFun
is True
for any character of the string object given in input, the character is included in the output. Otherwise, the characters aren’t included in the output.
To remove all the occurrences of a given character in a string, we will follow the following steps.
- First, we will define a function
myFun
that takes a character as an input argument. It returnsFalse
if the input character is equal to the character that has to be removed. Otherwise, it should returnTrue
. - After defining
myFun
, we will passmyFun
as the first argument and the string as the second input argument to thefilter()
function. - After execution, the
filter()
function will return an iterable object containing the characters that aren’t removed from the string. - We will create a list of characters by passing the iterable object to the
list()
constructor. - Once we get the list of characters, we will create the output string. For this, we will invoke the
join()
method on an empty string with the list of characters as its input argument. - After execution of the
join()
method, we will get the desired string.
You can observe the entire process in the following code.
def myFun(character):
charToDelete = 'c'
return charToDelete != character
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = list(filter(myFun, myStr))
print("The list is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
The modified string is: pythonforbeginners
Instead of defining the function myFun
, we can create an equivalent lambda function and pass it to the filter function to remove all the instances of the character from the string. You can do it as follows.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = list(filter(lambda character: character != charToDelete, myStr))
print("The list is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
The modified string is: pythonforbeginners
Delete All Occurrences of a Character From a String in Python Using the replace() Method
The replace()
method, when invoked on a string, takes the character that needs to be replaced as its first argument. In the second argument, it takes the character that will be replaced in place of the original character given in the first argument.
After execution, the replace()
method returns a copy of the string that is given as input. In the output string, all the characters are replaced with the new character.
To remove all the occurrences of a given character from a string, we will invoke the replace()
method on the string. We will pass the character that needs to be removed as the first input argument. In the second input argument, we will pass an empty string.
After execution, all the occurrences of character will be replaced by an empty string. Hence, we can say that the character has been removed from the string.
You can observe the entire process in the following example.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
outputString = myStr.replace(charToDelete, "")
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
Remove All Occurrences of a Character From a String in Python Using the translate() Method
We can also use the translate()
method to remove characters from a string. The translate()
method, when invoked on a string, takes a translation table as an input argument. After execution, it returns a modified string according to the translation table.
The translation table can be created using the maketrans()
method. The maketrans()
method, when invoked on a string, takes the character that needs to be replaced as its first argument and the new character as its second argument. After execution, it returns a translation table.
We will use the following steps to remove the given character from the string.
- First, we will invoke the
maketrans()
method on the input string. We will pass the character that needs to be removed as the first input argument and a space character as the second input argument to themaketrans()
method. Here, we cannot pass an empty character to themaketrans()
method so that it can map the character to empty string. This is due to the reason that the length of both the strings arguments should be the same. Otherwise, themaketrans()
method will run into error. - After execution, the
maketrans()
method will return a translation table that maps the character we need to remove to a space character. - Once we get the translation table, we will invoke the
translate()
method on the input string with the translation table as its input argument. - After execution, the
translate()
method will return a string where the characters that we need to remove are replaced by space characters. - To remove the space characters from the string, we will first invoke the
split()
method on the output of thetranslate()
method. After this step, we will get a list of substrings. - Now, we will invoke the
join()
method on an empty string. Here, we will pass the list of substrings as input to thejoin()
method. - After execution of the
join()
method, we will get the desired string.
You can observe the entire process in the following code.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
translationTable = myStr.maketrans(charToDelete, " ")
outputString = "".join(myStr.translate(translationTable).split())
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
Delete All Occurrences of a Character From a String in Python Using Regular Expressions
Regular expressions provide one of the most efficient ways to manipulate strings or text data.
To remove a character from a string, we can use the sub()
method defined in the re
module. The sub()
method takes the character that needs to be replaced say old_char
as its first input argument. It takes the new character new_char
as its second input argument, and the input string as its third argument. After execution, it replaces the old_char
with new_char
in the input string and returns a new string.
To remove all the occurrences of a character from a given string, we will use the following steps.
- We will pass the character that needs to be removed as the first input argument
old_char
to thesub()
method. - As the second argument
new_char
, we will pass an empty string. - We will pass the input string as the third argument to the
sub()
method.
After execution, the sub()
method will return a new string. In the new string, the character that needs to be removed will get replaced by the empty string character. Hence, we will get the desired output string.
You can observe this in the following code.
import re
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
outputString = re.sub(charToDelete, "", myStr)
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
Conclusion
In this article, we have discussed different ways to remove all the occurrences of a character from a list. Likewise, we have discussed different approaches to remove all the occurrences of a character in a string. For lists, I would suggest you use the approach with the remove()
method. For strings, you can use either the replace()
method or the re.sub()
method as these are the most efficient approaches to remove all the occurrences of a character in a list or a string in python
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.