[python] Python 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?

This question is related to python string python-2.7 set

The answer is


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])

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()

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)'

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict

Examples related to set

java, get set methods golang why don't we have a set datastructure Simplest way to merge ES6 Maps/Sets? Swift Set to Array JavaScript Array to Set How to sort a HashSet? Python Set Comprehension How to get first item from a java.util.Set? Getting the difference between two sets Python convert set to string and vice versa