How do i remove a specific character from a list in python?

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]

msg = filter(lambda x : x != "8", lst)

print msg

EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.

Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped.

To make this (kinda work?) with how the intent of the question was we could perform something similar to this

msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
  • I am not in an interpreter at the moment so of course mileage may vary, we may have to index so we do list(y[0]) would be the only modification to the above for this explanation purposes.

What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"].

This would result in a data type that looks like this

msg = [["a", "a", "a", "a"], ["b", "b"]...]

So finally to wrap that up we would have to map it to bring them all back into the same type roughly

msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))

I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.

In this article, we will discuss different ways to remove a character from a list of strings in python.

Suppose we have a list of strings,

list_of_str = ['what', 'why', 'now', 'where', 'who', 'how', 'wow']

Now, we want to remove all occurrences of character ‘w’ rom this list of strings. After that list should be like this,

['hat', 'hy', 'no', 'here', 'ho', 'ho', 'o']

There are different ways to do this. Let’s discuss them one by one,

Remove a character from list of strings using list comprehension and replace()

Strings are immutable in python, so we can not modify them in place. But we can create a new string with the modified contents. So create a new list with the modified strings and then assign it back to the original variable.

Advertisements

For that, use the list comprehension to iterate over all strings in the list. Then for each string, call the replace() function to replace all occurrences of the character to be deleted with an empty string. Finally list comprehension will return a new list of modified strings. Let’s see it in working code,

list_of_str = ['what', 'why', 'now', 'where', 'who', 'how', 'wow']

ch = 'w'
# Remove character 'w' from the list of strings
list_of_str = [elem.replace(ch, '') for elem in list_of_str]

print(list_of_str)

Output:

['hat', 'hy', 'no', 'here', 'ho', 'ho', 'o']

It deleted all occurrences of character ‘w’ from the list of strings.

Remove a character from list of strings using map() function

We can also use the map() function to remove a character from all the strings in a list. Steps are as follows,

  • Create a lambda function, that accepts a string and returns a copy of the string after removing the given character from it.
  • Pass the lambda function and the list of strings as arguments to the map() function.
  • map() function will iterate over all string in the list and call the lambda function on it. Which returns a new string after removing the giving character. Finally map() function returns mapped object containing modified strings.
  • Pass the mapped object to the list() to create a new list of strings.
  • This strings in list do not contain the given character. So, eventually we deleted a given character from the list of strings.

Working example is as follows,

list_of_str = ['what', 'why', 'now', 'where', 'who', 'how', 'wow']

# Remove character 'w' from the list of strings
list_of_str  = list(map(lambda elem: elem.replace(ch, ''), list_of_str))

print(list_of_str)

Output:

['hat', 'hy', 'no', 'here', 'ho', 'ho', 'o']

It deleted all occurrences of character ‘w’ from the list of strings.

Summary:

We learned about two different ways to delete a character from a list of strings in python.

You are here: Home / Basics / Remove All Occurrences of a Character in a List or String in Python

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. 

Table of Contents

  1. Remove an Element From a List Using the pop() Method
  2. Delete an Element From a List Using the remove() Method
  3. Remove All Occurrences of a Character From List
    1. Delete All Occurrences of a Character From a List Using List Comprehension
    2. Remove All Occurrences of an Element From a List Using the remove() Method
    3. Delete All Occurrences of a Character Using the filter() Function
  4. Remove All Occurrences of a Character From a String in Python
    1. Delete All Occurrences of a Character From a String in Python Using for Loop
    2. Remove All Occurrences of a Character From a String in Python Using List Comprehension
    3. Delete All Occurrences of a Character From a String in Python Using the split() Method
    4. Remove All Occurrences of a Character From a String in Python Using the filter() Function
    5. Delete All Occurrences of a Character From a String in Python Using the replace() Method
    6. Remove All Occurrences of a Character From a String in Python Using the translate() Method
    7. Delete All Occurrences of a Character From a String in Python Using Regular Expressions
  5. 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:

How do i remove a specific character from a list in python?

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 
    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 
    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. 

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 the list() 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 the append() 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 returns False if the input character is equal to the character that we need to remove. Otherwise, it should return True
  • After defining myFun, we will pass myFun as the first argument and the list of characters as the second input argument to the filter() 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. The join() 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 the join() method on the empty character with the list obtained from the previous step as its input argument. After execution of the join() 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 the split() method. We will store the output of the split() method in myList.
  • After obtaining myList, we will invoke the join() method on an empty string with myList as the input argument to the join() method.
  • After execution of the join() method, we will get the desired output. So, we will store it in a variable outputString.

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 returns False if the input character is equal to the character that has to be removed. Otherwise, it should return True
  • After defining myFun, we will pass myFun as the first argument and the string as the second input argument to the filter() 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 the maketrans() method. Here, we cannot pass an empty character to the maketrans() 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, the maketrans() 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 the translate() 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 the join() 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 the sub() 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!

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.

How do I remove an item from a list in Python?

Items of the list can be deleted using del statement by specifying the index of item (element) to be deleted. We can remove an item from the list by passing the value of the item to be deleted as the parameter to remove() function. pop() is also a method of list.

How do I remove a specific string from a list?

Method #1 : Using remove() This particular method is quite naive and not recommended to use, but is indeed a method to perform this task. remove() generally removes the first occurrence of K string and we keep iterating this process until no K string is found in list.

How do I remove a specific value from a list index?

You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output. You can also use negative index values.