Sunday, November 17, 2024
Google search engine
HomeLanguagesConvert String to Set in Python

Convert String to Set in Python

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 = "Lazyroar"
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 : Lazyroar

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 = "Lazyroar"
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 : Lazyroar

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. 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments