9

My input files have lines that looks like this:

[(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)]
[(0, 1, 6), (1, 3,7), (3, 1,4), (3, 1,3), (8, 1,2)]
[1,2,3,5,3]

There are no letters, no decimals, only integers and number of element in tuples will be consistent.

How do i make them into real list of tuples / list of int?

1 Answer 1

21

Python comes with batteries included - that problem is solved by ast.literal_eval():

>>> import ast
>>> ast.literal_eval("[(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)]")
[(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)]
>>> ast.literal_eval("[(0, 1, 6), (1, 3,7), (3, 1,4), (3, 1,3), (8, 1,2)]")
[(0, 1, 6), (1, 3, 7), (3, 1, 4), (3, 1, 3), (8, 1, 2)]
>>> ast.literal_eval("[1,2,3,5,3]")
[1, 2, 3, 5, 3]
3
  • 3
    @alvas: Please note that ast.literal_eval is safe whereas eval is not. Commented Nov 27, 2013 at 18:38
  • @StevenRumbalski Why is ast.literal_eval safe and eval not safe?
    – jeppoo1
    Commented Feb 19, 2020 at 7:41
  • 1
    @jeppo1: Often the string you are wanting to evaluate comes from an untrusted source. eval will run arbitrary code. Running arbitrary code from third parties is a security hole. ast.literal_eval, plugs that hold because it only interprets "strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None." Anything else is an error. Commented Feb 19, 2020 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.