Python Practice › String Programs › Program 68

First repeated word

EasyString Programs · 68 of 106

Write a Python program to find the first word that repeats.

Advertisement
Input
"ab bc ca ab bd"
Output
ab

Approach

  1. Remember words seen; return the first one seen again.

Solution

Python
def first_repeated(text):    seen = set()    for w in text.split():        if w in seen:            return w        seen.add(w)    return None print(first_repeated("ab bc ca ab bd"))
Output
ab

Learn the concept

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

More string programs

← All 106 String Programs

Leave a Comment