Is it possible to parse the below string, using Python, or convert it into another data structure so that each element can be accessed for analysis?
This is an example line from a large text file where each line has the same format.
string = ["('a', '1')", "('b', '2')"]
If you simply want to convert the tuple-strings to tuples, you can use ast.literal_eval
:
>>> import ast
>>> [ast.literal_eval(x) for x in string]
[('a', '1'), ('b', '2')]
Use of ast.literal_eval
rather than eval
is encouraged as it is considered safer: it does not execute all strings of Python code, only literal expressions (no variables, no function calls).
You can then access the elements of the tuples using Python's slice/index notation, or convert to an alternative data structure, e.g. a dictionary:
>>> dict([ast.literal_eval(x) for x in string])
{'a': '1', 'b': '2'}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments