Convert String to Set in Python
Last Updated :
19 Feb, 2025
Improve
There are multiple ways of converting a String to a Set in python, here are some of the methods.
Using set()
The easiest way of converting a string to a set is by using the set() function.
Example 1 :
s = "Geeks"
print(type(s))
print(s)
# Convert String to Set
set_s = set(s)
print(type(set_s))
print(set_s)
Output
<class 'str'> Geeks <class 'set'> {'s', 'e', 'k', 'G'}
Let’s explore other methods of converting string to set:
Table of Content
Using set() with split() method (for words)
To convert words from a sentence into a set, use spilt() method before set().
Example:
s = "Geek for Geeks"
# split the string and then convert it to set
set_words = set(s.split())
print(set_words)
Output
{'for', 'Geeks', 'Geek'}
Using dict.fromkeys()
We can also convert a string to a set by using dict.fromkeys() as it creates a dictionary from an iterable and sets the values to none for every key.
Example:
# create a string
s = "developer"
set_s = set(dict.fromkeys(s))
print(set_s)
Output
{'l', 'v', 'o', 'd', 'e', 'p', 'r'}