The Wayback Machine - https://web.archive.org/web/20241122230802/https://www.geeksforgeeks.org/python-remove-given-character-from-strings-list/
Open In App

Python | Remove given character from Strings list

Last Updated : 14 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Sometimes, while working with Python list, we can have a problem in which we need to remove a particular character from each string from list. This kind of application can come in many domains. Let’s discuss certain ways to solve this problem. 

Method #1 : Using replace() + enumerate() + loop 

This is brute force way in which this problem can be solved. In this, we iterate through each string and replace specified character with empty string to perform removal. 

Step-by-step approach:

  1. Initialize a character named char which is to be removed from the strings in the list.
  2. Iterate over the list using a for loop and enumerate() function to get the index and corresponding element in each iteration.
  3. For each iteration, replace the character ‘s’ with an empty string ” in the corresponding element using the replace() method and update the list with the modified element at the same index using the index obtained from enumerate().
  4. Print the modified list of strings.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Remove character from Strings list
# using loop + replace() + enumerate()
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize character
char = 's'
 
# Remove character from Strings list
# using loop + replace() + enumerate()
for idx, ele in enumerate(test_list):
    test_list[idx] = ele.replace(char, '')
 
# printing result
print("The list after removal of character : " + str(test_list))


Output : 

The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']

Time complexity: O(n*m), where n is the length of the input list and m is the average length of the strings in the list. 
Auxiliary space: O(1). The algorithm modifies the original list in place and does not create any new data structures. 

Method #2: Using list comprehension + replace() 

This task can also be performed using the above functionalities. In this, we offer a one-liner solution to this problem compacting the code using similar method as above. 

Python3




# Python3 code to demonstrate working of
# Remove character from Strings list
# using list comprehension + replace()
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize character
char = 's'
 
# Remove character from Strings list
# using list comprehension + replace()
res = [ele.replace(char, '') for ele in test_list]
 
# printing result
print("The list after removal of character : " + str(res))


Output : 

The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']

Time complexity: O(n*m), where n is the length of the original list and m is the length of the longest string in the list

Auxiliary space: O(n*m).

Method #3: Using map(),lambda functions.

Python3




# Python3 code to demonstrate working of
# Remove character from Strings list
# using list comprehension + replace()
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize character
char = 's'
 
res = list(map(lambda x: x.replace(char, ''), test_list))
 
# printing result
print("The list after removal of character : " + str(res))


Output

The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method#4: Using Recursive method.

Algorithm:

  1. Define a function to remove the character from the given list of strings.
  2. The function takes two inputs, the list of strings lst and the character to be removed char.
  3. Check if the list is empty. If yes, return an empty list.
  4. If the list is not empty, remove the character from the first string in the list using the replace method, and add it to a list.
  5. Recursively call the function with the rest of the list, and add the result to the list created in the previous step.
  6. Return the modified list of strings.

Python3




# Python3 code to demonstrate working of
# Remove character from Strings list
def remove_char(lst, char):
    if not lst:
        return []
    else:
        return [lst[0].replace(char, '')] + remove_char(lst[1:], char)
 
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize character
char = 's'
 
res =remove_char(test_list,char)
 
# printing result
print("The list after removal of character : " + str(res))


Output

The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']

Time Complexity:
The time complexity of this function is O(n * m), where n is the number of strings in the list and m is the maximum length of any string in the list. This is because for each string, the replace method scans the entire string character by character, which takes up to m time. We need to perform this operation for each of the n strings in the list, resulting in a time complexity of O(n * m).

Auxiliary Space:
The space complexity of this function is O(n * m), where n is the number of strings in the list and m is the maximum length of any string in the list. This is because we create a new list to store the modified strings, and the size of each modified string could be up to m characters. We need to create this list for each of the n strings in the list, resulting in a space complexity of O(n * m).

Method #6: Using regex

  1. Import the re module.
  2. Define the function remove_char(lst, char) that takes a list of strings and a character as arguments.
  3. Use the re.sub() function to replace the specified character in each string in the list with an empty string.
  4. Return the modified list.

Python3




import re
 
def remove_char(lst, char):
    return [re.sub(char, '', s) for s in lst]
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize character
char = 's'
 
res = remove_char(test_list,char)
 
# printing result
print("The list after removal of character : " + str(res))


Output

The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']

Time complexity: O(nm), where n is the number of strings in the list and m is the average length of the strings. The re.sub() function has a time complexity of O(m) for each string in the list.

Auxiliary space: O(nm), where n is the number of strings in the list and m is the average length of the strings. This is the space required to store the modified strings in the new list.

Method #7: Using reduce():

Algorithm:

  1. Import the “reduce” function from the “functools” module and the “re” module for regular expressions.
  2. Define the “remove_char” function that takes a list of strings and a character as input.
  3. Use the “reduce” function to iterate over each string in the list and apply the “re.sub()” function to remove the specified character.
  4. Append the modified string to a new list.
  5. Return the new list with the modified strings.
  6. Initialize a list of strings “test_list”.
  7. Print the original list.
  8. Initialize a character “char”.
  9. Call the “remove_char” function with the “test_list” and “char” as arguments.
  10. Print the modified list.

Python3




from functools import reduce
import re
 
def remove_char(lst, char):
    return reduce(lambda x, y: x + [re.sub(char, '', y)], lst, [])
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize character
char = 's'
 
res = remove_char(test_list,char)
 
# printing result
print("The list after removal of character : " + str(res))
#This code is contributed by Rayudu.


Output

The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']

Time complexity:
The time complexity of the “remove_char” function is O(nm), where “n” is the length of the input list and “m” is the length of the longest string in the list. The “reduce” function takes O(n) time to iterate over each string in the list, and the “re.sub()” function takes O(m) time to remove the specified character from each string.

Space complexity:
The space complexity of the “remove_char” function is O(nm), where “n” is the length of the input list and “m” is the length of the longest string in the list. The function creates a new list to store the modified strings, which takes up O(nm) space.



Previous Article
Next Article

Similar Reads

Python | Remove last character in list of strings
Sometimes, we come across an issue in which we require to delete the last character from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plus. Let's discuss certain ways in which this can be
8 min read
Python | Remove Kth character from strings list
Sometimes, while working with data, we can have a problem in which we need to remove a particular column, i.e the Kth character from string list. String are immutable, hence removal just means re creating a string without the Kth character. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + list sl
7 min read
Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Python - Remove strings with any non-required character
Given a Strings list, remove string, if it contains any unwanted character. Input : test_list = ["gfg", "is", "best", "for", "geeks"], chr_list = ['f', 'm', 'n', 'i'] Output : ['best', 'geeks'] Explanation : Given Strings don't contain f, m, n or i. Input : test_list = ["gfg", "is", "best", "for", "geeks"], chr_list = ['f', 'm', 'n'] Output : ['bes
6 min read
Python | Remove List elements containing given String character
Sometimes, while working with Python lists, we can have problem in which we need to perform the task of removing all the elements of list which contain at least one character of String. This can have application in day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute force way in w
7 min read
Python - Find all the strings that are substrings to the given list of strings
Given two lists, the task is to write a Python program to extract all the strings which are possible substring to any of strings in another list. Example: Input : test_list1 = ["Geeksforgeeks", "best", "for", "geeks"], test_list2 = ["Geeks", "win", "or", "learn"] Output : ['Geeks', 'or'] Explanation : "Geeks" occurs in "Geeksforgeeks string as subs
5 min read
Python | Remove tuple from list of tuples if not containing any character
Given a list of tuples, the task is to remove all those tuples which do not contain any character value. Example: Input: [(', ', 12), ('...', 55), ('-Geek', 115), ('Geeksfor', 115),] Output: [('-Geek', 115), ('Geeksfor', 115)] Method #1 : Using list comprehension C/C++ Code # Python code to remove all those # elements from list of tuple # which doe
4 min read
Python - Remove Initial character in String List
In Python, Sometimes, we come across an issue in which we require to delete the initial character from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plus. Let’s discuss certain ways in whic
7 min read
Python | Pair the consecutive character strings in a list
Sometimes while programming, we can face a problem in which we need to perform consecutive element concatenation. This problem can occur at times of school programming or competitive programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + zip() Combination of above functionalities can be u
5 min read
Python program to find the character position of Kth word from a list of strings
Given a list of strings. The task is to find the index of the character position for the word, which lies at the Kth index in the list of strings. Examples: Input : test_list = ["geekforgeeks", "is", "best", "for", "geeks"], K = 21 Output : 0Explanation : 21st index occurs in "geeks" and point to "g" which is 0th element of word. Input : test_list
3 min read
Python - Sort by Rear Character in Strings List
Given a String list, perform sort by the rear character in the Strings list. Input : test_list = ['gfg', 'is', 'for', 'geeks'] Output : ['gfg', 'for', 'is', 'geeks'] Explanation : g < r < s = s, hence the order. Input : test_list = ['gfz', 'is', 'for', 'geeks'] Output : ['for', 'is', 'geeks', 'gfz'] Explanation : r < s = s < z, hence th
6 min read
Python - Remove given character from first element of Tuple
Given a Tuple list, remove K character from 1st element of the Tuple being String. Input : test_list = [("GF$g!", 5), ("!i$s", 4), ("best!$", 10)], K = '$' Output : [('GFg!', 5), ('!is', 4), ('best!', 10)] Explanation : First element's strings K value removed. Input : test_list = [("GF$g!", 5), ("best!$", 10)], K = '$' Output : [('GFg!', 5), ('best
5 min read
Python | Remove all digits from a list of strings
Given a list of strings, write a Python program to remove all digits from the list of string. Examples: Input : ['alice1', 'bob2', 'cara3'] Output : ['alice', 'bob', 'cara'] Input : ['4geeks', '3for', '4geeks'] Output : ['geeks', 'for', 'geeks'] Method #1: Python Regex Python regex pattern can also be used to find if each string contains a digit or
5 min read
Python | Remove all strings from a list of tuples
Given a list of tuples, containing both integer and strings, the task is to remove all strings from list of tuples. Examples: Input : [(1, 'Paras'), (2, 'Jain'), (3, 'GFG'), (4, 'Cyware')] Output : [(1), (2), (3), (4)] Input : [('string', 'Geeks'), (2, 225), (3, '111')] Output : [(), (2, 225), (3,)] Method #1: Using filter() method C/C++ Code # Pyt
8 min read
Python | Remove trailing/leading special characters from strings list
Sometimes, while working with String lists, we can have a problem in which we need to perform the deletion of extra characters that can be termed as unwanted and occur at end of each string. Let's discuss a way in which this task can be performed. Method 1: Using map() + str.strip() A combination of the above two functionalities can help us achieve
5 min read
Python | Remove prefix strings from list
Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings starting with a specific prefix are removed. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + remove() + startswith() The combination of the above functions can solve this problem.
5 min read
Python - Remove duplicate words from Strings in List
Sometimes, while working with Python list we can have a problem in which we need to perform removal of duplicated words from string list. This can have application when we are in data domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using set() + split() + loop The combination of above methods can be used to perfo
6 min read
Python - Remove leading 0 from Strings List
Sometimes, while working with Python, we can have a problem in which we have data which we need to perform processing and then pass the data forward. One way to process is to remove a stray 0 that may get attached to a string while data transfer. Let's discuss certain ways in which this task can be performed. Method #1 : Using lstrip() + list compr
5 min read
Python | Remove Redundant Substrings from Strings List
Given list of Strings, task is to remove all the strings, which are substrings of other Strings. Input : test_list = ["Gfg", "Gfg is best", "Geeks", "for", "Gfg is for Geeks"] Output : ['Gfg is best', 'Gfg is for Geeks'] Explanation : "Gfg", "for" and "Geeks" are present as substrings in other strings.Input : test_list = ["Gfg", "Geeks", "for", "Gf
5 min read
Python - Remove Non-English characters Strings from List
Given a List of Strings, perform removal of all Strings with non-english characters. Input : test_list = ['Good| ????', '??Geeks???'] Output : [] Explanation : Both contain non-English characters Input : test_list = ["Gfg", "Best"] Output : ["Gfg", "Best"] Explanation : Both are valid English words. Method #1 : Using regex + findall() + list compre
8 min read
Remove Duplicate Strings from a List in Python
Dealing with duplicate strings in a list is a common task in Python, often come across this when working with string/text data. In this article, we'll explore multiple approaches to remove duplicate strings from a list in Python. Remove Duplicate Strings From a List in PythonBelow are some of the ways by which we can remove duplicate strings from a
2 min read
Python | Tokenizing strings in list of strings
Sometimes, while working with data, we need to perform the string tokenization of the strings that we might get as an input as list of strings. This has a usecase in many application of Machine Learning. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension + split() We can achieve this particular task using lis
3 min read
Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character
In this article, we will code a python program to create a dictionary with the key as the first character and value as words starting with that character. Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds t
6 min read
Python | Insert character after every character pair
Sometimes, we can have a problem in which we need to insert a specific character after a pair(second) characters using Python. This kind of problem can occur while working with data, that require insertion of commas or any other special character mainly in the Machine Learning domain. Let's discuss certain ways in which this problem can be solved.
6 min read
Python program to read character by character from a file
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by character from the input as shown in the output.Read a fi
2 min read
Python | Filter a list based on the given list of strings
Given a List, the task is to filter elements from list based on another list of strings. These type of problems are quite common while scraping websites. Examples: Input: List_string1 = ['key', 'keys', 'keyword', 'keychain', 'keynote'] List_string2 = ['home/key/1.pdf', 'home/keys/2.pdf', 'home/keyword/3.pdf', 'home/keychain/4.pdf', 'home/Desktop/5.
3 min read
Python program to remove the nth index character from a non-empty string
Given a String, the task is to write a Python program to remove the nth index character from a non-empty string Examples: Input: str = "Stable" Output: Modified string after removing 4 th character Stabe Input: str = "Arrow" Output: Modified string after removing 4 th character Arro The first approach uses a new string variable for storing the modi
4 min read
Python program to Remove Last character from the string
Given a string, the task is to write a Python program to remove the last character from the given string. Example: Input: "GeeksForGeeks"Output: "GeeksForGeek" Input: "1234"Output: "123"Explanation: Here we are removing the last character of the original string. Note: Strings are immutable in Python, so any modification in the string will result in
3 min read
Python | Convert string List to Nested Character List
Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() The combination of above functional
7 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Practice Tags :
three90RightbarBannerImg