Python Program to Find the First Non-Repeating Character
Intermediate · Strings
The first non-repeating character of a string is the first character that appears only once in it. In "swiss" the letter s appears three times, so the answer is w. This is a common interview question, solved here with two passes over the string.
Program
String: swiss First non-repeating character: 'w' at index 1
How it works
- The first loop counts how many times each character appears and stores the counts in a dictionary.
- The second loop goes through the string again, in its original order, and stops at the first character whose count is 1.
enumerate()gives the index as well as the character, so the program can report the position too.- If every character repeats,
answerstaysNoneand the program says so. - Each loop reads the string only once, so the program stays fast even on very long strings.
Other ways to write it
Using Counter and next()
swiss: w aabbcdd: c racecar: e aabb: None
next() takes the first value the generator produces, and its second argument, None, is returned when no character qualifies, as with "aabb".
Using count()
First non-repeating character: w
The else of a for loop runs only when the loop ends without break. This version is shorter, but count() rescans the string for every character, which is slow for long strings.
Try it yourself
Change the program to find the first character that does repeat, such as s in "swiss".
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Find Duplicate Characters in a String
- Count the Frequency of Each Character in a String
- Remove Duplicate Characters from a String
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Words in a String
- Remove Punctuation from a String
All Python programs · CBSE class 12 practical file · Python exercises