# Python program to replace all Characters of a List except the given character

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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)

## 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.

Updated on 08-Sep-2021 07:17:39