Python Practice › String Programs › Program 10

Replace the second occurrence of each character

MediumString Programs · 10 of 106

Write a Python program to replace the second occurrence of every character with “$”.

Advertisement
Input
"Programming"
Output
Prog$am$in$

Approach

  1. Count characters as you go; when a count reaches 2, write “$” instead.

Solution

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

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs