Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert set to string and vice versa

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?

like image 310
ov7a Avatar asked Jul 08 '13 13:07

ov7a


2 Answers

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. 
like image 150
Ashwini Chaudhary Avatar answered Sep 27 '22 22:09

Ashwini Chaudhary


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)' 
like image 42
Adem Öztaş Avatar answered Sep 27 '22 21:09

Adem Öztaş