Related Articles

Related Articles

Convert Set to String in Python
  • Last Updated : 15 Oct, 2020

In this article, we will discuss how to convert a set to a string in Python. It can done using two ways –

Method 1: Using str()
We will convert a Set into a String in Python using the str() function.

Syntax : str(object, encoding = ’utf-8?, errors = ’strict’)

Parameters :

  • object : The object whose string representation is to be returned.
  • encoding : Encoding of the given object.
  • errors : Response when decoding fails.

Returns : String version of the given object



Example 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# create a set
s = {'a', 'b', 'c', 'd'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
  
# convert Set to String
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s)

chevron_right


Output :

Initially
The datatype of s : <class 'set'>
Contents of s :  {'c', 'd', 'a', 'b'}

After the conversion
The datatype of s : <class 'str'>
Contents of s : {'c', 'd', 'a', 'b'}

Example 2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# create a set
s = {'g', 'e', 'e', 'k', 's'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
  
# convert Set to String
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s)

chevron_right


Output :

Initially
The datatype of s : <class 'set'>
Contents of s :  {'k', 'g', 's', 'e'}

After the conversion
The datatype of s : <class 'str'>
Contents of s : {'k', 'g', 's', 'e'}

Method 2: Using Join()

The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.

Syntax:

string_name.join(iterable) 
filter_none

edit
close

play_arrow

link
brightness_4
code

# create a set
s = {'a', 'b', 'c', 'd'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
   
# convert Set to String
S = ', '.join(s)
print("The datatype of s : " + str(type(S)))
print("Contents of s : ", S)

chevron_right


Output:

Initially
The datatype of s : <class 'set'>
Contents of s :  {'c', 'd', 'a', 'b'}
The datatype of s : <class 'str'>
Contents of s :  c, d, a, b

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :