Python Practice › String Programs › Program 10
Replace the second occurrence of each character
Write a Python program to replace the second occurrence of every character with “$”.
Input
"Programming"
Output
Prog$am$in$
Approach
- Count characters as you go; when a count reaches 2, write “$” instead.
Solution
text = "Programming"seen = {}result = ""for ch in text: seen[ch] = seen.get(ch, 0) + 1 result += "$" if seen[ch] == 2 else chprint(result)Output
Prog$am$in$
Line by line
Line 5
Count each character as it appears.
Line 6
Only the exact second occurrence becomes “$”; the third “m” or “g” would stay.
Learn the concept
New to this topic? Read the lesson, then come back.