Python convert set to string and vice versa
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.
Try like this,
>>> s = set([1,2,3])
>>> s = list(s)
>>> s
[1, 2, 3]
>>> str = ', '.join(str(e) for e in s)
>>> str = 'set(%s)' % str
>>> str
'set(1, 2, 3)'
The question is little unclear because the title of the question is asking about string and set conversion but then the question at the end asks how do I serialize ? !
let me refresh the concept of Serialization is the process of encoding an object, including the objects it refers to, as a stream of byte data.
If interested to serialize you can use:
json.dumps -> serialize
json.loads -> deserialize
If your question is more about how to convert set to string and string to set then use below code (it's tested in Python 3)
String to Set
set('abca')
Set to String
''.join(some_var_set)
example:
def test():
some_var_set=set('abca')
print("here is the set:",some_var_set,type(some_var_set))
some_var_string=''.join(some_var_set)
print("here is the string:",some_var_string,type(some_var_string))
test()