w3resource

Python: Find the first repeated character in a given string


Find first repeated character.

Write a Python program to find the first repeated character in a given string.

Visual Presentation:

Python String: Find the first repeated character in a given string
Python String: Find the first repeated character in a given string

Sample Solution:

Python Code:

# Define a function 'first_repeated_char' that takes a string 'str1' as input.
def first_repeated_char(str1):
    # Iterate through each character 'c' and its index 'index' in the input string 'str1'.
    for index, c in enumerate(str1):
        # Check if the count of character 'c' in the substring of 'str1' up to 'index+1' is greater than 1.
        if str1[:index + 1].count(c) > 1:
            return c  # Return the first repeated character found.

    return "None"  # Return "None" if no repeated character is found.

# Call the 'first_repeated_char' function with different input strings and print the results.
print(first_repeated_char("abcdabcd"))
print(first_repeated_char("abcd")) 

Sample Output:

a
None  

Flowchart:

Flowchart: Find the first repeated character in a given string

For more Practice: Solve these Related Problems:

  • Write a Python program to iterate through a string and return the first character that repeats using a set for tracking.
  • Write a Python program to find the first repeated character by maintaining a count dictionary during iteration.
  • Write a Python program to implement a function that returns the first repeated character along with its repetition count.
  • Write a Python program to use recursion to determine the first character that appears more than once in a given string.

Go to:


Previous: Write a Python program to print all permutations with given repetition number of characters of a given string.
Next:Write a Python program to find the first repeated character of a given string where the index of first occurrence is smallest.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.