non repeated character in string in python

To find the first non-repeated character in a string, we can loop through the characters of the string and store their count in a dictionary. Then, we can loop through the dictionary and return the first character which has a count of 1.

Here's the Python code to find the first non-repeated character in a string:

main.py
def first_non_repeated_char(string):
    # Create a dictionary to store the count of each character
    char_count = {}
    for char in string:
        if char in char_count:
            char_count[char] += 1
        else:
            char_count[char] = 1

    # Find the first non-repeated character
    for char in string:
        if char_count[char] == 1:
            return char

    # No non-repeated character found
    return None
438 chars
17 lines

You can call this function by passing a string as an argument, and it will return the first non-repeated character in the string. If no non-repeated character is found, it returns None. Here's an example:

main.py
string = "hello world"
print(first_non_repeated_char(string))  # Output: 'h'
77 chars
3 lines

gistlibby LogSnag