The Wayback Machine - https://web.archive.org/web/20210303132805/https://www.geeksforgeeks.org/count-the-number-of-unique-characters-in-a-string-in-python/
Skip to content
Related Articles

Related Articles

Count the number of unique characters in a string in Python
  • Last Updated : 03 Mar, 2021

Given a string S consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string.

Examples:

Input: S = “geeksforgeeks”
Output: 7
Explanation: The given string “geeksforgeeks” contains 6 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}.

Input: S = “madam”
Output: 1

Approach: The idea to solve the given problem is to initialize a Set() in python to store all distinct characters of the given string and then, print the size of the set as the required answer.



Below is the implementation of the above approach:

Python3




# Python program for the above approach
  
# Function to count the number of distinct
# characters present in the string str
def countDis(str):
  
    # Stores all distinct characters
    s = set(str)
  
    # Return the size of the set
    return len(s)
  
  
# Driver Code
if __name__ == "__main__":
  
    # Given string S
    S = "geeksforgeeks"
  
    print(countDis(S))


Output:

7

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :