Open In App

Convert String to Set in Python

Last Updated : 12 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 : 

python




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

python




# 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'}

Method: Using set brackets and start operator. 

Algorithm: 

  • Initialize test string. 
  • Use the start operator to string traverse the string character by character and uses set brackets to hold them 
  • Print result. 

Python3




# 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 = {*string}
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string)


Output

Initially
The datatype of string : <class 'str'>
Contents of string : geeks

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

Time complexity: O(N) Where N is the length of a string. 

Auxiliary space: O(M) Where M is the length of a new set. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads