Python Practice › String Programs › Program 100
First repeated character and its index
Write a Python program to find the first character that repeats and the index of its first occurrence.
Input
"sqatools"
Output
('o', 4)Approach
- Remember the first index of each character; stop at the first repeat.
Solution
text = "sqatools"first_seen = {}for i, ch in enumerate(text): if ch in first_seen: print((ch, first_seen[ch])) break first_seen[ch] = iOutput
('o', 4)Line by line
Lines 4-6
The first character seen twice is reported with the index where it first appeared.
Note
The loop finds the repeat at the second “o”, so the answer is (“o”, 4): “o” repeats before “s” does.
Learn the concept
New to this topic? Read the lesson, then come back.