Replace Character

Replace all occurrences of a character.

IntermediatePhase 5 - Category 4: String TransformationExample 1 of 10
replace-character.py
1# Take string input
2s = input("Enter a string: ")
3old_char = input("Enter character to replace: ")
4new_char = input("Enter new character: ")
5
6# Replace
7result = s.replace(old_char, new_char)
8print(f"After replacement: {result}")

Output

Enter a string: Hello
Enter character to replace: l
Enter new character: x
After replacement: Hexxo

What's going on

Use replace() method to replace characters.

Key Concepts:

replace(old, new) replaces all occurrences
Returns new string
Original unchanged