Get the unique characters in a String in Python

avatar

Borislav Hadzhiev

Last updated: Sep 21, 2022

banner

Photo from Unsplash

Get the unique characters in a String in Python #

To get the unique characters in a string:

  1. Use the set() class to convert the string to a set of unique characters.
  2. Use the str.join() method to join the characters into a string.
  3. The new string will consist of the unique characters of the original string.
main.py
my_str = 'bobby' # ✅ Get unique characters in a string (order not preserved) result = ''.join(set(my_str)) print(result) # 👉️ byo # ----------------------------------------- # ✅ Get unique characters in a string (order preserved) result = ''.join(dict.fromkeys(my_str).keys()) print(result) # 👉️ boy

The first example uses the set() class to get the unique characters in a string.

The set() class takes an iterable optional argument and returns a new set object with elements taken from the iterable.

main.py
my_str = 'bobby' print(set(my_str)) # 👉️ {'y', 'b', 'o'}
Set objects store an unordered collection of unique elements, so converting the string to a set removes all duplicate characters.

The last step is to use the str.join() method to join the set into a string.

main.py
my_str = 'bobby' result = ''.join(set(my_str)) print(result) # 👉️ byo result = list(set(my_str)) print(result) # 👉️ ['y', 'b', 'o']

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

We used an empty string separator to join the set into a string without a delimiter.

If you need to get the unique characters of the string in a list, use the list() class.

main.py
my_str = 'bobby' result = list(set(my_str)) print(result) # 👉️ ['y', 'b', 'o']

The list class converts the set object to a list.

Set objects are unordered. If you need to preserve the order of the characters, use the dict.fromkeys() method.

Get the unique characters in a String using dict.fromkeys() #

To get the unique characters in a string:

  1. Use the dict.fromkeys() method to create a dictionary from the string.
  2. Use the str.join() method to join the keys of the dictionary into a string.
  3. The new string will consist of the unique characters of the original string.
main.py
my_str = 'bobby' result = ''.join(dict.fromkeys(my_str).keys()) print(result) # 👉️ boy

The dict.fromkeys method takes an iterable and a value and creates a new dictionary with keys from the iterable and values set to the provided value.

main.py
my_str = 'bobby' # 👇️ {'b': None, 'o': None, 'y': None} print(dict.fromkeys(my_str))

Dictionary keys are unique, so any duplicate characters get removed.

We used the dict.keys() method to get a view of the dictionary's keys and joined the object into a string.

Dictionaries preserve the insertion order of keys in Python 3.7 and more recent versions.

If you use an older version, use the OrderedDict class to get the unique characters in the string while preserving the order.

main.py
from typing import OrderedDict my_str = 'bobby' result = ''.join(OrderedDict.fromkeys(my_str).keys()) print(result) # 👉️ boy

The OrderedDict class is a subclass of dict and is simply a dictionary that remembers insertion order.

Using the OrderedDict class is not necessary if you use a version of Python greater than 3.7.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.