Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to convert a printed list in Python back into an actual list

So given the a a textual representation of a list

['cellular organisms', 'Bacteria', 'Bacteroidetes/Chlorobi group', 'Bacteroidetes',   'Bacteroidia', 'Bacteroidales', 'Bacteroidaceae', 'Bacteroides', 'Bacteroides vulgatus']

What is the easiest way to convert this text back into an actual list within a python script? Is split really the best way? Thanks!

like image 356
Wes Field Avatar asked Mar 11 '14 10:03

Wes Field


1 Answers

>>> import ast
>>> a = "['cellular organisms', 'Bacteria', 'Bacteroidetes/Chlorobi group', 'Bacteroidetes',   'Bacteroidiroidales', 'Bacteroidaceae', 'Bacteroides', 'Bacteroides vulgatus']"
>>> ast.literal_eval(a)
['cellular organisms', 'Bacteria', 'Bacteroidetes/Chlorobi group', 'Bacteroidetes', 'Bacteroidia', 'Bacteroidales', 'Bacteroidaceae', 'Bacteroides', 'Bacteroides vulgatus']

From the ast module:

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

like image 54
MattH Avatar answered Sep 28 '22 07:09

MattH