Python: Find the first repeated word in a given string
Find first repeated word in string.
Write a Python program to find the first repeated word in a given string.
Visual Presentation:
Sample Solution:
Python Code:
# Define a function 'first_repeated_word' that takes a string 'str1' as input.
def first_repeated_word(str1):
# Create an empty set 'temp' to store unique words encountered.
temp = set()
# Iterate through each word in the string 'str1' by splitting it using spaces.
for word in str1.split():
# Check if the word is already in the 'temp' set.
if word in temp:
return word # Return the first repeated word found.
else:
temp.add(word) # Add the word to the 'temp' set if it's not already there.
return 'None' # Return 'None' if no repeated word is found.
# Call the 'first_repeated_word' function with different input strings and print the results.
print(first_repeated_word("ab ca bc ab"))
print(first_repeated_word("ab ca bc ab ca ab bc"))
print(first_repeated_word("ab ca bc ca ab bc"))
print(first_repeated_word("ab ca bc"))
Sample Output:
ab ab ca None
Flowchart:
Python Code Editor:
Previous: Write a Python program to find the first repeated character of a given string where the index of first occurrence is smallest.
Next:Write a Python program to find the second most repeated word in a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics