Python program to Replace all Characters of a List Except the given character
Last Updated :
02 Jun, 2023
Given a List. The task is to replace all the characters of the list with N except the given character.
Input : test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'], repl_chr = '*', ret_chr = 'G'
Output : ['G', '*', 'G', '*', '*', '*', '*', '*', '*']
Explanation : All characters except G replaced by *
Input : test_list = ['G', 'F', 'G', 'B', 'E', 'S', 'T'], repl_chr = '*', ret_chr = 'G'
Output : ['G', '*', 'G', '*', '*', '*', '*']
Explanation : All characters except G replaced by *
Method #1 : Using list comprehension + conditional expressions
In this, we perform the task of iteration using list comprehension, and replacements are taken care of using conditional operators.
Python3
# Python3 code to demonstrate working of
# Replace all Characters Except K
# Using list comprehension and conditional expressions
# initializing lists
test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
# printing original list
print("The original list : " + str(test_list))
# initializing repl_chr
repl_chr = '$'
# initializing retain chararter
ret_chr = 'G'
# list comprehension to remake list after replacement
res = [ele if ele == ret_chr else repl_chr for ele in test_list]
# printing result
print("List after replacement : " + str(res))
OutputThe original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
List after replacement : ['G', '$', 'G', '$', '$', '$', '$', '$', '$']
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1) additional space is not needed.
In this, we use map() and lambda function to extend the logic to each element of the list.
Python3
# Python3 code to demonstrate working of
# Replace all Characters Except K
# Using map() + lambda
# initializing lists
test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
# printing original list
print("The original list : " + str(test_list))
# initializing repl_chr
repl_chr = '$'
# initializing retain chararter
ret_chr = 'G'
# using map() to extend logic to each element of list
res = list(map(lambda ele: ret_chr if ele == ret_chr else repl_chr, test_list))
# printing result
print("List after replacement : " + str(res))
OutputThe original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
List after replacement : ['G', '$', 'G', '$', '$', '$', '$', '$', '$']
Method 3: Using a for loop to iterate through the list and replace the characters accordingly
Python3
# Python3 code to demonstrate working of
# Replace all Characters Except K
# Using for loop
# initializing lists
test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
# printing original list
print("The original list : " + str(test_list))
# initializing repl_chr
repl_chr = '$'
# initializing retain chararter
ret_chr = 'G'
# creating an empty list to store the modified characters
res = []
# iterating through the list and replacing the characters
for ele in test_list:
if ele == ret_chr:
res.append(ele)
else:
res.append(repl_chr)
# printing result
print("List after replacement : " + str(res))
OutputThe original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
List after replacement : ['G', '$', 'G', '$', '$', '$', '$', '$', '$']
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list, since we are creating a new list to store the modified characters.
Method #4 using the replace() function
Step-by-step approach
- Define the input list: test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
- Define the character to replace non-matching characters: repl_chr = '$'
- Define the character to retain: ret_chr = 'G'
- Use a list comprehension to iterate over each element ele in the test_list.
- For each element, check if it is equal to ret_chr.
- If it is equal, replace it with ret_chr using the replace() function: ele.replace(ele, ret_chr).
- If it is not equal, replace it with repl_chr using the replace() function: ele.replace(ele, repl_chr).
- The resulting list of replaced characters is stored in res.
- Print the original list: print("The original list:", test_list).
- Print the list after replacement: print("List after replacement:", res).
Python3
test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
repl_chr = '$'
ret_chr = 'G'
res = [ele.replace(ele, ret_chr) if ele == ret_chr else ele.replace
(ele, repl_chr) for ele in test_list]
print("The original list:", test_list)
print("List after replacement:", res)
OutputThe original list: ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
List after replacement: ['G', '$', 'G', '$', '$', '$', '$', '$', '$']
Time complexity: The time complexity of this method is O(n), where n is the length of the input list test_list.
Auxiliary space: The auxiliary space complexity is O(n), where n is the length of the input list.
Similar Reads
Python program to extract characters in given range from a string list
Given a Strings List, extract characters in index range spanning entire Strings list. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], strt, end = 14, 20 Output : sbest Explanation : Once concatenated, 14 - 20 range is extracted.Input : test_list = ["geeksforgeeks", "is", "best",
4 min read
Python - Convert list of strings and characters to list of characters
Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Using itertools.chain()itertools.chain() combines multiple lists or iterables i
3 min read
Python Program To Remove all control characters
In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is
3 min read
Python Program to Replace all Occurrences of âaâ with $ in a String
Given a string, the task is to write a Python program to replace all occurrence of 'a' with $. Examples: Input: Ali has all aces Output: $li h$s $ll $ces Input: All Exams are over Output: $ll Ex$ms $re Over Method 1: uses splitting of the given specified string into a set of characters. An empty str
3 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg"
8 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 approa
4 min read
Python program to remove last N characters from a string
In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions.Using String SlicingString slicing is one of the simplest and mos
2 min read
Replace a String character at given index in Python
In Python, strings are immutable, meaning they cannot be directly modified. We need to create a new string using various methods to replace a character at a specific index. Using slicingSlicing is one of the most efficient ways to replace a character at a specific index.Pythons = "hello" idx = 1 rep
2 min read
Python Program to remove a specific digit from every element of the list
Given a list of elements, the task here is to write a Python program that can remove the presence of all a specific digit from every element and then return the resultant list. Examples: Input : test_list = [333, 893, 1948, 34, 2346], K = 3 Output : ['', 89, 1948, 4, 246] Explanation : All occurrenc
7 min read
Python Program to Replace Text in a File
In this article, we are going to replace Text in a File using Python. Replacing Text could be either erasing the entire content of the file and replacing it with new text or it could mean modifying only specific words or sentences within the existing text.Method 1: Removing all text and write new te
3 min read