SOLVED: List unique characters from a string in Python


Python

Different methods to list unique characters from a String in Python

A string in Python is a sequence of characters. It is a derived data type. Strings are immutable. This means that once defined, we cannot change a part of the string.
There are four approaches to get unique characters from a string. They are as listed below.

  • Using set data structure
  • Using Counter class
  • Using OrderedDict class
  • Using Looping

 

Method-1: Using set data structure

As we know, that the set data structure only stores the unique elements in it. It does not allow repeated values. So, we can utilize this feature to list unique characters from a string. Here, we will parse a string character by character and store it in the set. Hence, it will store only unique characters of a string.

Example : In this example, we will store the string "welcome to the world" as a set. So, only unique characters will be written to the set.


# Program to list unique characters from a string using set data structure
# Initializing the string
input_string = "welcome to the world"

# Storing in the set s1
unique_chars_set = set(input_string)

# Printing set s1
print("List of unique characters are ")
print(unique_chars_set)

Output

List of unique characters are 
{'o', 'd', 'e', 'w', 'h', 'l', 'r', 'm', ' ', 't', 'c'}

 

Method-2: Using Counter Class

In this approach, we will use Counter function of the Counter class of collections framework. A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages. Here, we will count elements from the string.

Example : In this example, the counter function will store the unique characters in dictionary with key as a character and its frequency as a value.

# Program to list unique characters from a string using Counter function of Counter class
from collections import Counter
# Initializing the string
input_string = "welcome to the world"

# Using counter
char_counter = Counter(input_string)

# Printing the result
print ("List of unique characters along with its frequency \n")
print(char_counter)

Output

List of unique characters are 
Counter({'e': 3, 'o': 3, ' ': 3, 'w': 2, 'l': 2, 't': 2, 'c': 1, 'm': 1, 'h': 1, 'r': 1, 'd': 1})

 

Method-3: Using OrderedDict class

In this approach, we will use OrderedDict class of collection framework. Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. Here, we are using join function to join the results and fromkeys method will create a new dictionary with keys from seq and values set to value.

Example : In this example, we will use join along with the fromkeys method to store the list of unique characters.

# Program to list unique characters from a string using OrderedDict class of collections
from collections import OrderedDict
# Initializing the string
input_string = "welcome to the world"

# Using fromkeys() method of OrderedDict class
unique_chars_ordered = ' '.join(OrderedDict.fromkeys(input_string).keys())

# Printing the result
print ("List of unique characters are \n")
print(unique_chars_ordered)

Output

List of unique characters are 
w e l c o m   t h r d

 

Method-4: Using Looping

This is the traditional approach, we will simply parse the characters of string one by one and store it in another list such that the character is not repeated in the list. Thereafter, we will print the result stored in the unique list.

Example : In this example, we are using core python concepts like for loop, if statement, not in to accomplish our task.

# Program to list unique characters from a string using looping
# Initializing the string
string_to_process = "welcome to the world"

# Using looping
unique = []
for c in string_to_process:
    if not c in unique:
        unique.append(c)
        
# Printing the result
print ("List of unique characters are \n")
print(unique)

Output

List of unique characters are 
['w', 'e', 'l', 'c', 'o', 'm', ' ', 't', 'h', 'r', 'd']

 

Summary

The knowledge of listing unique characters from the string is very useful while working on real time applications. In many situations, we will need to count the unique characters from a string or find unique characters from a string. In this tutorial, we covered four different approaches to list unique characters from a string. We learned in detail about this with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on how to list unique characters from a string in Python.

 

References

collections - Container datatypes
Sets in Python

 

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment