Use repr
and eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
Note that eval
is not safe if the source of string is unknown, prefer ast.literal_eval
for safer conversion:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])
help on repr
:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.