Leonardo Romanello
Leonardo Romanello

Reputation: 137

How to get a data structure from inside a string (Python)

I have a program which outputs a list in a .txt file on a server and I want to save that list in a new variable.
I'm doing:

with open ("file.txt", "r") as myfile:
    data = myfile.read().replace('\n', '')
var = data

but obviously print(var) returns a string "[list, of, stuff]"

Yeah I can bypass the txt-save procedure but what in case I could not?

Upvotes: 2

Views: 2084

Answers (1)

sundar nataraj
sundar nataraj

Reputation: 8702

you can use AST

import ast
var="[list, of, stuff]"
var=ast.literal_eval(var)
print var[0]
#output list

From docs

ast.literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

If you're original data was serialized using JSON then you could also use the json module from the Python standard library.

Even if it was just print(some_list) you could still use the json library; i.e:

>>> from json import dumps, loads
>>> xs = [1, 2, 3]
>>> loads(dumps(xs)) == loads(repr(xs))
True

Upvotes: 6

Related Questions