Say someone gives me a string like:
"[[A,B],[C,D]]"
and I want to extract the list it describes:
[[A,B],[C,D]]
How do I do this?
P.S.
A, B, C, D are just placeholders, they could be numeric values or strings.
Say someone gives me a string like:
"[[A,B],[C,D]]"
and I want to extract the list it describes:
[[A,B],[C,D]]
How do I do this?
P.S.
A, B, C, D are just placeholders, they could be numeric values or strings.
To prevent an ValueError: malformed string
from being raised when passing the input directly to ast.literal_eval
, "
s need to be added around the characters in the string:
import ast, re
s = "[[A,B],[C,D]]"
new_s = ast.literal_eval(re.sub('\w+', '{}', s).format(*['"{}"'.format(i) for i in re.findall('\w+', s)]))
Output:
[['A', 'B'], ['C', 'D']]
Based on A
, B
, C
, and D
being numbers (int
, or float
) or strings (str
), you can simply use:
l = eval("[[A,B],[C,D]]")
For example:
In [1]: l = eval("[[1,2],[3,4]]")
In [2]: l
Out[2]: [[1, 2], [3, 4]]
In [3]: l = eval("[['Hello', 10],['bye', 100]]")
In [4]: l
Out[4]: [['Hello', 10], ['bye', 100]]
In [5]: l = eval("[[3.14, 1],['bye', 2.72]]")
In [6]: l
Out[6]: [[3.14, 1], ['bye', 2.72]]