How to convert a list to string and vice versa?

I have a list: ('47075', 'josenestle', 'i need help') I do str1 = str (list) and have in string.

However if I do list (str1) I do not recover my list.

I can't find any obvious solution, help would be very grateful.

Author: Victor Stafusa, 2017-04-30

2 answers

As commented, The answer presented does not solve the problem presented. If you have an object, you want to convert it to a string and later convert it back, you will need to use some serialization technique. In Python, the most common library for this is the pickle. To serialize, aka convert the object to a representation in string, use the function pickle.dumps() and to convert back to the original object the function pickle.loads() is used, see documentation.

Whereas you own the object:

obj = ('47075', 'josenestle', 'i need help')

You can serialize it with:

obj_serialized = pickle.dumps(obj)

This way you will have a string of bytes that represents your object. For example, the value of obj_serialized will be:

b'\x80\x03X\x05\x00\x00\x0047075q\x00X\n\x00\x00\x00josenestleq\x01X\x0b\x00\x00\x00i need helpq\x02\x87q\x03.'

After you do everything necessary with the serialized object , you can retrieve the object with:

obj_recuperado = pickle.loads(obj_serialized)

Getting:

('47075', 'josenestle', 'i need help')

Which represents exactly the original object. Realize that it is not the same object, but rather an object with the same value. You can prove this by checking its relationship to the original object:

print(obj == obj_recuperado)  # True
print(obj is obj_recuperado)  # False
 1
Author: Woss, 2018-02-17 21:04:35

I found the answer!

>>> import ast
>>> x = u'[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']

Using "ast.literal_eval " I have a safe way to evaluate strings literally.

 -1
Author: hiperbolt, 2017-04-30 09:37:37