What is the best way to go about the following?
I want to let a user input a nested list as follows:
grid = input(\'Enter grid\')
The
As inspectorG4dget commented, use ast.literal_eval:
>>> import ast
>>> ast.literal_eval("[['', 'X', 'O'], ['X', 'O', ''], ['X', '', 'X']]")
[['', 'X', 'O'], ['X', 'O', ''], ['X', '', 'X']]
To filter out invalid input, catch SyntaxError:
>>> ast.literal_eval("[['', 'X', 'O'], ['X', 'O', ''], ['X', ', 'X']]")
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.4/ast.py", line 46, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python3.4/ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "", line 1
[['', 'X', 'O'], ['X', 'O', ''], ['X', ', 'X']]
^
SyntaxError: invalid syntax