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 :
# 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) |
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 :
# 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) |
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.