Skip to content
Related Articles

Related Articles

Convert String to Set in Python
  • Last Updated : 20 Aug, 2020

We can convert a string to setin Python using the set() function.

Syntax : set(iterable)

Parameters : Any iterable sequence like list, tuple or dictionary.

Returns : An empty set if no element is passed. Non-repeating element iterable modified as passed as argument.

Example 1 :



filter_none

edit
close

play_arrow

link
brightness_4
code

# create a string str
string = "geeks"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
  
# convert String to Set
string = set(string)
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string)

chevron_right


Output :

Initially
The datatype of string : 
Contents of string : geeks

After the conversion
The datatype of string : 
Contents of string :  {'k', 's', 'g', 'e'}

Example 2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# create a string str
string = "Hello World!"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
  
# convert String to Set
string = set(string)
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string)

chevron_right


Output :

Initially
The datatype of string : 
Contents of string : Hello World!

After the conversion
The datatype of string : 
Contents of string :  {'r', 'H', ' ', 'l', 'o', '!', 'd', 'W', 'e'}

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 :