Python Practice › String Programs › Program 100

First repeated character and its index

EasyString Programs · 100 of 106

Write a Python program to find the first character that repeats and the index of its first occurrence.

Advertisement
Input
"sqatools"
Output
('o', 4)

Approach

  1. Remember the first index of each character; stop at the first repeat.

Solution

Python
text = "sqatools"first_seen = {}for i, ch in enumerate(text):    if ch in first_seen:        print((ch, first_seen[ch]))        break    first_seen[ch] = i
Output
('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.

Advertisement

Learn the concept

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

More string programs

← All 106 String Programs