Convert set to string and vice versa
Asked Answered
A

6

47

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?

Australopithecus answered 8/7, 2013 at 13:49 Comment(1)
just a note, I've downvoted because the terminology used is wrong. serialization/deserialization makes me immediately think of passing objects to/from JSON or via pickle, but that's a misleading assumption in this case.Ellisellison
B
53

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.
Booth answered 8/7, 2013 at 13:51 Comment(0)
Y
13

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()
Yul answered 26/1, 2019 at 5:52 Comment(0)
G
7

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)'
Gemmulation answered 8/7, 2013 at 13:52 Comment(2)
I don't think this is what the OP wants to do.Alkali
Question is : Python convert set to string and vice versa.Booth
T
6

1) Set to String:

s = set({1,2,3,4}) # set with int values.

Convert each value of set as a string, and join them to return one string with , as a delimiter.
str_val = ', '.join(list(map(str, s)))

output of str_val: '1, 2, 3, 4'

2) String to Set:

Split the string with , as a delimiter. It creates a list. Then convert the list as a set.

s = set(str_val.split(","))

output of s: {' 2', ' 3', ' 4', '1'}

Tagmemics answered 25/3, 2021 at 20:51 Comment(0)
M
3

If you do not need the serialized text to be human readable, you can use pickle.

import pickle

s = set([1,2,3])

serialized_s = pickle.dumps(s)
print "serialized:"
print serialized_s

deserialized_s = pickle.loads(serialized_s)
print "deserialized:"
print deserialized_s

Result:

serialized:
c__builtin__
set
p0
((lp1
I1
aI2
aI3
atp2
Rp3
.
deserialized:
set([1, 2, 3])
Misfile answered 8/7, 2013 at 14:18 Comment(0)
F
0

if the len of the set 1

>>> s
{'[email protected]'}
>>> list(s)[0]
'[email protected]'

if the set has more than one value

>>> def set2str(l, spe=' - '):
       s=''
       for i in l:
            s += f'{i}{spe}'
       return s[:len(s) - len(spe)]
>>> s.add('asfasf')
>>> set2str(s)
'asfasf - [email protected]'
>>> set2str(s,' ') # you can change the spe
'asfasf [email protected]'
Felder answered 23/2, 2022 at 21:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.