user1919
user1919

Reputation: 3938

How to convert a list into string and this string back to the initial list?

I have the following issue with Python and I was wondering if there is a direct way to deal with it (using a specific function which I am not aware of, etc.).

I have a list with different types of inputs (integer, string, etc.). I transform the list into a string using the str() function. Now the type of the variable is a string. I do some processing with this string and then I want to transform the string back into the initial list with the initial variable types it had (integer, string, etc.).

Here is an illustration:

             list = [1,'house',3]
             print(type(list))  # gives <class list>
             print(type(list[0])) # gives <type int>
             print(type(list[1])) # gives <type str>

             string = str(list)
             print(type(string)) # gives <type string>
             ... # use this string to process data


            # convert the string into the initial list
             ? ?

I thought maybe I could in the beginning iterate my list and store the type of its attributes in a list (list_b). Later when I convert the string to a list I will explode the string and convert the strings to the variable types corresponding to the list_b.

I was wondering if there is a more straight forward way than this?

Upvotes: 1

Views: 1732

Answers (2)

Hart Simha
Hart Simha

Reputation: 902

This seems like a good use case for Python's 'json' module, as it can transform lists and dictionaries into JSON (which is a string format) and vice versa.

So for example:

import json
x = [1,2,3]
y = json.dumps(x) # => '[1, 2, 3]'
z = json.loads(y) # => [1,2,3]

This only works with simple data structures (dict, list, tuple, str, int, long, float, boolean, and None) (more information on this here)

You can check out this answer if your list will contain other kinds of objects that you want to make serializable.

Upvotes: 2

Ffisegydd
Ffisegydd

Reputation: 53688

You can use ast.literal_eval to convert a string into a Python object.

from ast import literal_eval

s = "[1, 'house', 3]"
l = literal_eval(s)
print(l)
# [1, 'house', 3]

Note that, as per the docs linked above, the string can only be formed of strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

Upvotes: 7

Related Questions