Set to string. Obvious:
>>> s = set([1,2,3])
>>> s
set([1, 2, 3])
>>> str(s)
'set([1, 2, 3])'
String to set? Maybe like this?
>>> set(map(int,str(s).split('set([')[-1].split('])')[0].split(',')))
set([1, 2, 3])
Extremely ugly. Is there better way to serialize/deserialize sets?
Try like this,
Use
repr
andeval
:Note that
eval
is not safe if the source of string is unknown, preferast.literal_eval
for safer conversion:help on
repr
:If you do not need the serialized text to be human readable, you can use
pickle
.Result: