Convert Set to String in Python

Sets are an unordered collection of elements in Python. It does not contain duplicate elements and can be defined using the set() function in Python.

Ways to convert set to string in Python

This tutorial will discuss how to convert a set to string and view it as the latter in Python. We can verify the result using the type() function.

Using the str() function

In Python, we use the str() function to typecast objects and convert them to strings. Internally, it invokes the __str__() function.

For example,

Output:

{8, 5, 6}

In the above example,

  • The set() function defines a set object.
  • We convert it to a string using the str() function.
  • We verify this using the type() function.

Using the repr() function

The repr() function returns the official string representation of an object. Unlike the str() function, it invokes the __repr__() method internally. We can evaluate this string as Python code using the eval() function.

We can use this method to convert a set to a string.

For example,

Output:

{8, 5, 6}

In the above example, if the source of the string is unknown then the eval() function is not considered a safe option and should be avoided. The ast.literal_eval() is a safer alternative.

Using the join() function

The join() function combines the elements of an iterable based on a specified delimiter. The final result is a string.

We can combine elements of the set using this function and view the final string.

See the code below.

Output:

8, 5, 6

In the above example, we typecast every element to a string using the str() function before combining them using the join() function.

Using the map() function

The map() function will apply a function to all the methods of an iterable. We can typecast every element into a string and combine them into a final string.

See the code below.

Output:

8, 5, 6

In the above example,

  • We apply the str() function to typecast every element to a string using the map() function.
  • We store the above mentioned elements to a list.
  • Then, we combine the elements using the join() function.

Conclusion

In this tutorial, we discussed how to convert a set to a string. The str() and repr() functions are the most straightforward methods to achieve this conversion. The join() and map() methods are a little complicated but work nevertheless.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *