How To Convert a Set to a String in Python
In Python, a set refers to a collection of unordered data types that is iterable, mutable, and contains no duplicate elements. If you are familiar with the concept of sets in mathematics, a Python set is a data type that allows you to express math sets into code. Sets are handy when representing the membership and eliminating duplicate values.
When working with Python sets, you might encounter instances where you must convert the values into string types. For example, when logging output or similar operations that require string representation.
In this tutorial, we will walk you through the various methods and techniques you can use to convert Python sets into string types.
Basic Python Set
We define a set in Python by enclosing the values inside a pair of curly braces {}
. An example is as shown below:
num_set = {1, 2, 3, 4, 5}
print(num_set)
The above example defines a Python set called num_set
with numerical values.
Method 1 - Using str()
Function
The most straightforward and efficient method of converting a set into a string is using the built-in str()
function. This allows Python to quickly convert the values of the set into their string representation, as shown in the example below:
num_set = {1,2,3,4,5}
str_set = str(num_set)
print(str_set)
print(type(str_set))
This should return an output as shown:
{1, 2, 3, 4, 5}
<class 'str'>
As you can see, the resulting type is <class str>
.
Method 2 - Using the join()
Method
As we saw in the previous example, the str()
function provides a quick way to get the string representation of a set. However, there might be cases where we want a custom format.
This is where the join()
comes into play. However, since the method works on sets of strings, we need to convert each item into a string.
An example demonstration is as shown:
num_set = {1, 2, 3, 4, 5}
str_set = ', '.join(map(str, num_set))
print(str_set)
print(type(str_set))
The resulting output:
1, 2, 3, 4, 5
<class 'str'>
What if we want to represent the set in a different format? Say, separated by semicolons or maybe enclosed in square brackets?
We can achieve this custom formatting using the join()
method.
num_set = {1, 2, 3, 4, 5}
str_set = '[' + '; '.join(map(str, num_set)) + ']'
print(str_set)
print(type(str_set))
Output:
[1; 2; 3; 4; 5]
<class 'str'>
In this case, the join() method allows us to introduce customization into the string formatting and create more dynamic outputs.
Conclusion
This tutorial taught us how to use Python’s built-in join()
and str()
methods to convert a set into a string representation.