Count the number of Unique Characters in a String in Python
We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8.
Using set
Set in Python is an unordered collection of unique elements automatically removing duplicates when created from a string. The number of unique characters in string can be determined by finding length of set using len().
a = "hello world"
# Convert the string to a set
u_ch = set(a)
# Count the number of unique characters
u_c = len(u_ch)
print(f"Number of unique characters: {u_c}")
Output
Number of unique characters: 8
Explanation:
- Code converts the string "hello world" to a set (set(a)) to extract unique characters as sets automatically remove duplicates.
- It calculates number of unique characters using len(u_ch) and displays count using a formatted string.
Using collections.Counter
collections.Counter counts character frequencies in a string and stores them as key-value pairs. The number of unique characters is length of Counter object representing distinct keys.
from collections import Counter
a = "hello world"
ch = Counter(a)
u_c = len(ch)
print(f"Number of unique characters: {u_c}")
Output
Number of unique characters: 8
Explanation:
- Counter(a) counts the frequency of each character in string "hello world" and stores counts in a dictionary-like structure.
- Number of unique characters is determined using len(ch) which gives total number of distinct keys (characters) in Counter.
Using a manual loop
A manual loop iterates through each character in string and adds it to a list or set if it is not already present ensuring only unique characters are tracked. The number of unique characters is then determined by counting the length of resulting collection.
s = "hello world"
u_ch = []
for char in s:
# If the character is not already in the list, add it
if char not in u_ch:
u_ch.append(char)
# Calculate the number of unique characters
u_c = len(u_ch)
print(f"Number of unique characters: {u_c}")
Output
Number of unique characters: 8
Explanation:
- Loop iterates through each character in the string and appends it to the u_ch list only if it hasn't been added before ensuring all characters are unique.
- Length of u_ch list is calculated using len() representing number of unique characters in string.