
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to replace all Characters of a List except the given character
When it is required to replace all characters of a list except a given character, a list comprehension, and the ‘==’ operator are used.
Example
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)
Output
The list is : ['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'H', 'P'] The result is : ['P', '$', '$', '$', '$', '$', 'P', '$', 'P']
Explanation
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.
- Related Articles
- Python Program to Replace all words except the given word
- Java Program to replace all occurrences of a given character with new character
- How to replace characters except last with a mask character in JavaScript?
- Python Program – Strings with all given List characters
- Java Program to replace all occurrences of a given character in a string
- Program to replace all the characters in of a file with '#' except a particular word in Java
- Program to replace all digits with characters using Python
- How to replace all the special characters following another character – JavaScript?
- Python – Strings with all given List characters
- Program to find a list of product of all elements except the current index in Python
- C++ Program to Remove all Characters in a String Except Alphabets
- Replace all characters in a string except the ones that exist in an array JavaScript
- Python – Filter all uppercase characters from given list of tuples
- Python - Remove all characters except letters and numbers
- C program to replace all occurrence of a character in a string

Advertisements