Join Elements of a Set into a String in Python
Last Updated :
25 Jan, 2024
You might have encountered situations where you needed to join the elements of a set into a string by concatenating them, which are separated by a particular string separator. Let's say we want to convert the set {"GFG", "courses", "are", "best"} into a string with a space between each element that results in "GFG courses are best".
In this article, we will look at how to join the entries present in a set into a single string in Python.
Join Entries in a Set Into One String
Below are some ways by which we can join entries in a set into one string in Python:
- Naive Approach sep Keyword
- Using the join() function on a set object
- String DataType
- Integer DataType
- Using list comprehension with the join() function
Naive Approach
In the example below, Python code defines a function join_elements and takes two parameters, the set object and separator, to join a set consisting of strings using a for-loop. It creates a string joined_str that consists of set elements joined using separator `sep`.
Python3
def join_elements(set_obj, sep=','):
joined_str = ''
i = 0
for el in set_obj:
joined_str += el
if i < len(set_obj) - 1:
joined_str += sep
i += 1
return joined_str
set_obj = {'Java', 'Python', 'Scala', 'Rust', 'Lua'}
# print original set object
print("Original Set:", set_obj)
# sep is our separator character on joining elements
sep = "-"
# It joins elements of set_obj by `sep` and stores it in string named joined_str
joined_str = join_elements(set_obj, '-')
# print resultant joined string
print("Joined String:", joined_str)
OutputOriginal Set: {'Lua', 'Java', 'Rust', 'Python', 'Scala'}
Joined String: Lua-Java-Rust-Python-Scala
Join Entries on a Set Object Using join() method
We can use the join() method directly on a set object, as the join() method takes any iterable object like a set, list, or tuple as its input. We will see how to use the join() function with a couple of examples.
Join Set of Elements of String Datatype
The code below first prints the original set elements to create a list of strings from set elements. The string consisting of set elements joined by using the join() function separated by '-' as a separator, demonstrating the output string joined from set elements.
Python3
set_obj = {'Java', 'Python', 'Scala', 'Rust', 'Lua'}
# print original set object
print("Original Set:", set_obj)
# sep is our separator character on joining elements
sep = "-"
# It joins elements of set_obj by '-' and stores it in string named joined_str
joined_str = sep.join(set_obj)
# print resultant joined string
print("Joined String:", joined_str)
OutputOriginal Set: {'Java', 'Rust', 'Python', 'Lua', 'Scala'}
Joined String: Java-Rust-Python-Lua-Scala
Join Set of Elements of Integer Datatype
When the set includes integer elements, we first need to convert those integers to strings before using the join() method. Like the above example, the code first prints the original set of elements. Then, it prints the string consisting of set elements joined using the join() function separated by ' ,' as a separator, demonstrating the string joined from set elements.
Python3
set_obj = {11, 22, 33, 44, 55}
# print original set object
print("Original Set:", set_obj)
# sep is our separator character on joining elements
sep = ","
# It joins elements of set_obj by ',' and stores it in string named joined_str
joined_str = sep.join(str(s) for s in set_obj)
# print resultant joined string
print("Joined String:", joined_str)
OutputOriginal Set: {33, 11, 44, 22, 55}
Joined String: 33,11,44,22,55
Using List Comprehension with join() method
We can use list comprehension first to create a list of strings from set elements, and then we can use the join() function to join these entries into a single string.
Example: The below code first prints the original set elements and then joins the set elements by converting them into a list and then applying the join() function using '~' as a separator, and outputs the string joined from the list elements.
Python3
set_obj = {11, 22, 33, 44, 55}
# print original set object
print("Original Set:", set_obj)
# sep is our separator character on joining elements
sep = ","
# It joins elements of set_obj by ',' and stores it in string named joined_str
joined_str = '~'.join([str(el) for el in set_obj])
# print resultant joined string
print("Joined String:", joined_str)
OutputOriginal Set: {33, 11, 44, 22, 55}
Joined String: 33~11~44~22~55
Similar Reads
Split and join a string in Python The goal here is to split a string into smaller parts based on a delimiter and then join those parts back together with a different delimiter. For example, given the string "Hello, how are you?", you might want to split it by spaces to get a list of individual words and then join them back together
3 min read
Concatenate all Elements of a List into a String - Python We are given a list of words and our task is to concatenate all the elements into a single string with spaces in between. For example, given the list: li = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] after concatenation, the result will be: "hello geek have a geeky day".Using str.join()str.join()
2 min read
Put String in A Set in Python Imagine you have a magical box in Python that only stores unique items â that's exactly what a set is! Sets are like special containers designed to hold a bunch of different things without any duplicates. In Python, they provide a versatile and efficient way to manage collections of distinct element
3 min read
Find Common elements in three Lists using Sets - Python We are given three lists we need to find common elements in all three lists using sets. For example a = [1, 2, 3, 4], b = [2, 3, 5, 6] and c = [1, 2, 3, 7]. We need to find all common elements so that resultant output should be {2, 3}.Using set.intersection()set.intersection() method finds common el
3 min read
Create a List of Strings in Python Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
3 min read