![]() |
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 StringBelow are some ways by which we can join entries in a set into one string in Python:
Naive ApproachIn 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
Output
Original Set: {'Lua', 'Java', 'Rust', 'Python', 'Scala'} Joined String: Lua-Java-Rust-Python-Scala Join Entries on a Set Object Using join() methodWe 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
Output
Original 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
Output
Original Set: {33, 11, 44, 22, 55} Joined String: 33,11,44,22,55 Using List Comprehension with join() methodWe 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
Output
Original Set: {33, 11, 44, 22, 55} Joined String: 33~11~44~22~55 |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |