Sitemap
Shilpa Sreekumar

Shilpa Sreekumar

Python Developer at TimeClick Software

Member-only story

Python Coding Question #6

2 min readDec 6, 2024

First Non-Repeating Character in a String

Press enter or click to view image in full size
Photo by Kevin Ku on Unsplash

Question:

Write a python program to find the first non-repeating character in a string

Lets see the solutions:

  1. Using Counter class from collections module
from collections import Counter

def first_non_repeating_char(string):
char_counts = Counter(string)
for char in string:
if char_counts[char] == 1:
return char
return None


# Example usage:
string = "today"
result = first_non_repeating_char(string)
print(result)

# Output - t

Here in the solution, we first import the Counter class from collections module to efficiently count character frequencies and then create the Counter object char_counts to store the frequency of each character in the string and then iterate over each character in the string and check its frequency in the char_counts dictionary. If the frequency of a character is 1, it means it’s the first non-repeating character, so we return the unique first non-repeated character or else we return None.

2. Using a generator expression in one line

def first_non_repeating_char(s):
return next((char for char in s if s.count(char) == 1), None)

print(first_non_repeating_char('today')) # Output - t…

--

--

Shilpa Sreekumar
Shilpa Sreekumar

Written by Shilpa Sreekumar

Python Developer at TimeClick Software