Convert Set to String in Python
Converting a set to a string in Python means changing a group of unique items into a text format that can be easily read and used. Since sets do not have a fixed order, the output may look different each time. For example, a set {1, 2, 3} can be turned into the string “{1, 2, 3}” or into “{3, 1, 2}” etc.
Let’s discuss some of the methods of doing it with examples.
Using str()
The simplest and most direct method to convert a set into a string is using str(). It retains the curly braces {} and represents the set in a human-readable format.
a = {1, 2, 3}
res = str(a) # direct conversion
print(type(res), res)
Output
<class 'str'> {1, 2, 3}
Table of Content
Using f-string
f-strings (f”{a}”) offer a simple and readable way to convert a set to a string. They directly format the set as a string, maintaining its curly braces. This method is useful when quick and concise formatting is needed.
a = {1, 2, 3}
res = f"{a}"
print(type(res), res)
Output
<class 'str'> {1, 2, 3}
Using repr()
repr() function provides an official string representation of the set, including curly braces {}. This method is best suited for debugging and logging purposes since it ensures an exact representation of the set.
a = {1, 2, 3}
res = repr(a) # Returns official string representation
print(type(res), res)
Output
<class 'str'> {1, 2, 3}
Using join()
join() method is ideal when we want to convert a set into a clean, formatted string without curly braces {}. Since join() only works with strings, we first use map(str, a) to convert all elements to strings before joining them.
a = {1, 2, 3}
res = ", ".join(map(str, a))
print(type(res), res)
Output
<class 'str'> 1, 2, 3
Explanation:
- map(str, s) converts each element in the set to a string.
- join() merges all the converted strings into a single string, separated by ‘,‘.
Using json.dumps()
json.dumps() is a useful approach when we need a JSON-style string representation of a set. Since sets are not JSON serializable, we first convert the set into a list.
import json
a = {1, 2, 3}
res = json.dumps(list(a)) # Convert set to list, then JSON string
print(type(res), res)
Output
<class 'str'> [1, 2, 3]
Explanation:
- list(a) converts the set a to a list
- json.dumps() formats it as a string similar to a JSON array.