Python program to Replace all Characters of a List Except the given character
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 liststest_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'] # printing original listprint("The original list : " + str(test_list)) # initializing repl_chrrepl_chr = '$' # initializing retain chararterret_chr = 'G' # list comprehension to remake list after replacementres = [ele if ele == ret_chr else repl_chr for ele in test_list] # printing resultprint("List after replacement : " + str(res)) |
The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'] List after replacement : ['G', '$', 'G', '$', '$', '$', '$', '$', '$']
Method #2 : Using map() + lambda
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 liststest_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'] # printing original listprint("The original list : " + str(test_list)) # initializing repl_chrrepl_chr = '$' # initializing retain chararterret_chr = 'G' # using map() to extend logic to each element of listres = list(map(lambda ele: ret_chr if ele == ret_chr else repl_chr, test_list)) # printing resultprint("List after replacement : " + str(res)) |
The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'] List after replacement : ['G', '$', 'G', '$', '$', '$', '$', '$', '$']
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course



