在Python中将字符串转换为 Set
我们可以使用 set()函数将字符串转换为 setin Python 。
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.
示例 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)
输出 :
Initially
The datatype of string :
Contents of string : geeks
After the conversion
The datatype of string :
Contents of string : {'k', 's', 'g', 'e'}
示例 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)
输出 :
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'}