Parsing String Groupings (Python)

I have a line that looks something like this:

[["Name1","ID1","DDY1", "CALL1", "WHEN1"], ["Name2","ID2","DDY2", "CALL2", "WHEN2"],...];

      

This line was taken from the website. There can be any number of groupings. How can I parse this line and only print the Name variables of each group?

+2


a source to share


2 answers


Hope I understood well.



>>> import json
>>> a = json.loads('[["Name1","ID1","DDY1", "CALL1", "WHEN1"], ["Name2","ID2","DDY2", "CALL2", "WHEN2"]]')
>>> [x[0] for x in a]
[u'Name1', u'Name2']
>>> 

      

+5


a source


import ast
y = ast.literal_eval(input)
[x[0] for x in y]

      

Thanks to @stephan for pointing me in the right direction with ast.literal_eval. As described in the doc:



Safely evaluate expression node or string containing Python expression. A string or node can only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used to safely evaluate strings containing Python expressions from untrusted sources without having to parse the values.

Note. This is new functionality in Python 2.6.

+3


a source







All Articles