w3resource

Python: Find the first non-repeating character in given string


Find first non-repeating character.

Write a Python program to find the first non-repeating character in a given string.

Visual Presentation:

Python String: Find the first non-repeating character in given string
Python String: Find the first non-repeating character in given string

Sample Solution:

Python Code:

# Define a function 'first_non_repeating_character' that takes a string 'str1' as input.
def first_non_repeating_character(str1):
    # Create an empty list 'char_order' to store the order of characters encountered.
    char_order = []
    
    # Create an empty dictionary 'ctr' to count the occurrences of each character.
    ctr = {}

    # Iterate through each character 'c' in the input string 'str1'.
    for c in str1:
        # Check if the character 'c' is already in the 'ctr' dictionary.
        if c in ctr:
            # If it is, increment the count for that character.
            ctr[c] += 1
        else:
            # If it's not, add it to the 'ctr' dictionary and the 'char_order' list.
            ctr[c] = 1
            char_order.append(c)

    # Iterate through the characters in 'char_order'.
    for c in char_order:
        # Check if the character 'c' has a count of 1 (non-repeating).
        if ctr[c] == 1:
            return c  # Return the first non-repeating character.

    return None  # Return None if there are no non-repeating characters.

# Call the 'first_non_repeating_character' function with different input strings and print the results.
print(first_non_repeating_character('abcdef'))
print(first_non_repeating_character('abcabcdef'))
print(first_non_repeating_character('aabbcc')) 

Sample Output:

a
d
None              

Flowchart:

Flowchart: Find the first non-repeating character in given string

Python Code Editor:

Previous: Write a Python program to split a string on the last occurrence of the delimiter.
Next:Write a Python program to print all permutations with given repetition number of characters of a given string

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.