I have a list: ('47075', 'josenestle', 'i need help') I do str1 = str (list) and I have it in string.
However if you do list (str1) I do not retrieve my list.
I can not find an obvious solution, help would be very grateful.
I have a list: ('47075', 'josenestle', 'i need help') I do str1 = str (list) and I have it in string.
However if you do list (str1) I do not retrieve my list.
I can not find an obvious solution, help would be very grateful.
As commented out, the response presented does not solve the problem presented. If you have an object, you want to convert it to a string and then convert it back, you will need to use some serialization technique. In Python, the most common library for this is 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, use the function pickle.loads()
, see documentation.
Considering that you own the object:
obj = ('47075', 'josenestle', 'i need help')
You can serialize it with:
obj_serialized = pickle.dumps(obj)
In this way, you will have a bytes sequence 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 you need with the serialized object, you can retrieve the object with:
obj_recuperado = pickle.loads(obj_serialized)
Getting:
('47075', 'josenestle', 'i need help')
That represents exactly the original object. Notice that it is not the same object, but an object of the same value. You can check this by checking its relationship to the original object:
print(obj == obj_recuperado) # True
print(obj is obj_recuperado) # False
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 secure way of evaluating strings literally.