Open In App

Python program to Replace all Characters of a List Except the given character

Last Updated : 02 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


Output

The 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))


Output

The 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))


Output

The 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 

  1. Define the input list: test_list = [‘G’, ‘F’, ‘G’, ‘I’, ‘S’, ‘B’, ‘E’, ‘S’, ‘T’]
  2. Define the character to replace non-matching characters: repl_chr = ‘$’
  3. Define the character to retain: ret_chr = ‘G’
  4. Use a list comprehension to iterate over each element ele in the test_list.
  5. For each element, check if it is equal to ret_chr.
  6. If it is equal, replace it with ret_chr using the replace() function: ele.replace(ele, ret_chr).
  7. If it is not equal, replace it with repl_chr using the replace() function: ele.replace(ele, repl_chr).
  8. The resulting list of replaced characters is stored in res.
  9. Print the original list: print(“The original list:”, test_list).
  10. 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)


Output

The 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 - Replace occurrences by K except first character
Given a String, the task is to write a Python program to replace occurrences by K of character at 1st index, except at 1st index. Examples: Input : test_str = 'geeksforgeeksforgeeks', K = '@' Output : geeksfor@eeksfor@eeks Explanation : All occurrences of g are converted to @ except 0th index. Input : test_str = 'geeksforgeeks', K = '#' Output : ge
5 min read
Python - Replace all words except the given word
Given a string. The task is to replace all the words with '?' except the given word K. Examples: Input : test_str = 'gfg is best for geeks', K = "gfg", repl_char = "?" Output : gfg ? ? ? ? Explanation : All words except gfg is replaced by ?. Input : test_str = 'gfg is best for gfg', K = "gfg", repl_char = "?" Output : gfg ? ? ? gfg Explanation : Al
6 min read
Python | Remove all characters except letters and numbers
Given a string, the task is to remove all the characters except numbers and alphabets. String manipulation is a very important task in a day to day coding and web development. Most of the requests and responses in HTTP queries are in the form of Python strings with sometimes some useless data which we need to remove. Remove all characters except le
4 min read
Python | Extract characters except of K string
Sometimes, while working with Python strings, we can have a problem in which we require to extract all the elements of string except those which present in a substring. This is quite common problem and has application in many domains including those of day-day and competitive programming. Lets discuss certain ways in which this task can be performe
6 min read
Python Program to Removes Every Element From A String List Except For a Specified letter
Given a List that contains only string elements, the following program shows methods of how every other alphabet can be removed from elements except for a specific one and then returns the output. Input : test_list = ["google", "is", "good", "goggled", "god"], K = 'g' Output : ['gg', '', 'g', 'ggg', 'g'] Explanation : All characters other than "g"
4 min read
Remove character in a String except Alphabet
Given a string consisting of alphabets and other characters, remove all the characters other than alphabets and print the string so formed. Example Input: str = "$Gee*k;s..fo, r'Ge^eks?" Output: GeeksforGeeks Program to Remove characters in a string except alphabetsBelow are the steps and methods by which we can remove all characters other than alp
2 min read
Python program to replace every Nth character in String
Given a string, the task is to write a Python program to replace every Nth character in a string by the given value K. Examples: Input : test_str = "geeksforgeeks is best for all geeks", K = '$', N = 5 Output : geeks$orge$ks i$ bes$ for$all $eeks Explanation : Every 5th character is converted to $. Input : test_str = "geeksforgeeks is best for all
5 min read
Python3 Program to Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction
Given a square matrix mat[][] of dimension N and an integer K, the task is to rotate the matrix by 90 degrees K times without changing the position of the diagonal elements. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1Output: 1 16 11 6 5   22 7 12 9 2 23 18 1
4 min read
replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Practice Tags :