Join the elements of a Set into a string in Python


Borislav Hadzhiev

Last updated: Jun 18, 2022


Photo from Unsplash

Join the elements of a Set into a string in Python #

To join the elements of a set into a string:

  1. Call the str.join() method on a string separator.
  2. Pass the set to the join() method.
  3. The result will be a string containing the set elements separated by the provided separator.
my_set = {'a', 'b', 'c', 'd'} # 👇️ with space separator my_str = ' '.join(my_set) print(my_str) # 👉️ 'd a c b' # 👇️ without separator print(''.join(my_set)) # 👉️ 'dacb' # 👇️ with hyphen separator print('-'.join(my_set)) # 👉️ 'd-a-c-b'

Note that set objects are an unordered collection of unique elements, so the order might not be preserved.

If you need an ordered collection of elements, use a list instead, e.g. my_list = ['a', 'b', 'c', 'd'].

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

Note that the method raises a TypeError if there are any non-string values in the iterable.

If your set contains numbers, or other types, convert all of the values to string before calling join().
my_set = {'a', 'b', 'c', 'd', 1, 2} my_str = ' '.join(map(str, my_set)) print(my_str) # 👉️ '1 2 c d a b'

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

We used the function to convert each element in the set to a string, before passing the elements to the str.join() method.

The string the join() method is called on is used as the separator between the elements.
my_set = {'a', 'b', 'c', 'd'} my_str = '-'.join(my_set) print(my_str) # 👉️ 'b-c-a-d'

If you need to join the elements in the set with spaces, call the method on a string that contains a space.
my_set = {'a', 'b', 'c', 'd'} my_str = ' '.join(my_set) print(my_str) # 👉️ 'd a b c'

Similarly, you can use a newline (\n) to join the elements in the set with a newline character.
my_set = {'a', 'b', 'c', 'd'} my_str = '\n'.join(my_set) # b # a # c # d print(my_str)

If you don't need a separator and just want to join the iterable's elements into a string, call the join() method on an empty string.
my_set = {'a', 'b', 'c', 'd'} my_str = ''.join(my_set) print(my_str) # 👉️ 'bdac'
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.