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
Python - Convert case of elements in a list of strings
In Python, we often need to convert the case of elements in a list of strings for various reasons such as standardizing input or formatting text. Whether it's converting all characters to uppercase, lowercase, or even swapping cases. In this article, we'll explore several methods to convert the case
3 min read
Split String into List of characters in Python
We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g']. Using ListThe simplest way
2 min read
Breaking a Set into a List of Sets using Python
Given a set of elements p, the task is to write a Python program to convert the whole set into a list of Python Sets. Example: Input : p = {'sky', 'is', 'blue'} Output : [{'blue'}, {'is'}, {'sky'}] Explanation : Here each element of the set is converted into a individual set. Input : p = {10, 20, 30
2 min read
Split Elements of a List in Python
Splitting elements of a list in Python means dividing strings inside each list item based on a delimiter. split() Method is the easy and most straightforward method to split each element is by using the split() method. This method divides a string into a list based on a delimiter. Here's how we can
2 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(
3 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
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
Separate Alphabets and Numbers in a String - Python
The task is to separate alphabets and numbers from a string. For example, given "a1b2c3", the output should be alphabets "abc" and numbers "123". Using List ComprehensionList comprehension offers a concise and efficient way to separate alphabets and numbers from a string. It iterates through each ch
2 min read
Test if all elements are present in list-Python
The task of testing if all elements are present in a list in Python involves checking whether every item in a target list exists within a reference list. For example, given two lists a = [6, 4, 8, 9, 10] and b = [4, 6, 9], the task is to confirm that all elements in list b are also found in list a.
3 min read
Creating a List of Sets in Python
Creating a list of sets in Python involves storing multiple sets within list structure. Each set can contain unique elements and the list can hold as many sets as needed. In this article, we will see how to create a list of set using different methods in Python. Using List ComprehensionList comprehe
2 min read