Javaexercise.com

How to Convert Set to String in Python

In this topic, we will learn to convert Python set to string. The set is a data structure that is used to store unique elements while the string is a sequence of characters enclosed within single or double-quotes.

Here, we have several examples to understand the conversion between set to string and vice versa.

To convert a set to a string, we used join() method that is a string class method and used to get a string from an iterable. In the second example, we are using map() method with join() to cast non-string elements in the set. If we do not use the map() method then we get an error at runtime due to string conversion.

Let's see examples to understand the conversion of a set to string and vice versa.

Example: Python Set to String Conversion using join() Method

Here, we are converting set to string type using the join() method. This method returns a string from the iterable: set, list, etc. Here, the type() method is used to check the type of value after conversion to ensure that conversion is successful.

# Take a set
set_val = {"python","is","easy","to","learn"}
print(set_val)
print(type(set_val))
# Convert set to string
str_val = " ".join(set_val)
# Print value and it's type
print(str_val)
print(type(str_val))

Output:

{'easy', 'to', 'learn', 'is', 'python'}
<class 'set'>
easy to learn is python
<class 'str'>

Set to String conversion using join() and map() Methods

If we have a set that contains non-string elements such as integer or float then we must use map() method, otherwise the join() method raises a TypeError. Here, we are using the map() method inside the join() method to avoid any type of error.

# Take a set
set_val = {"python",3.8,"is","easy","to","learn"}
print(set_val)
print(type(set_val))
# Convert set to string
str_val = " ".join(map(str,set_val))
# Print value and it's type
print(str_val)
print(type(str_val))

Output:

{3.8, 'python', 'is', 'to', 'easy', 'learn'}
<class 'set'>
3.8 python is to easy learn
<class 'str'>

Converting String to Set in Python

After learning the conversion of a set to string. Now, let's learn the conversion of string to set which is exactly the reverse process of the previous one. Conversion of string to a set is very easy, we just need to use the set() method of the set class that returns a set of a specified type value.

# Take a string
str_val = "python"
print(str_val)
# Convert string to set
set_val = set(str_val)
# Print value and it's type
print(set_val)
print(type(set_val))

Output:

python
{'p', 'n', 't', 'y', 'h', 'o'}
<class 'set'>

 


Conclusion

Well, in this topic, we learnt to convert set to string and vice versa. We used join() and map() functions to convert set to string and set() method to convert string to set type.

If we missed something, you can suggest us at - info.javaexercise@gmail.com