When it is required to replace all characters of a list except a given character, a list comprehension, and the ‘==’ operator are used.
Below is a demonstration of the same −
my_list = ['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'H', 'P'] print("The list is :") print(my_list) replace_char = '$' retain_char = 'P' my_result = [element if element == retain_char else replace_char for element in my_list] print("The result is :") print(my_result)
The list is : ['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'H', 'P'] The result is : ['P', '$', '$', '$', '$', '$', 'P', '$', 'P']
A list of characters is defined and is displayed on the console.
Two more characters are defined, which are the characters that need to be replaced and retained respectively.
A list comprehension is used to iterate over the list, and if the current character is same as the character that needs to be retained, it is added to a list, else it is replaced with the other character.
These characters are stored in a list and are assigned to a variable
This is displayed as output on the console.