Convert string-tuple to a tuple

耗尽温柔 提交于 2019-12-06 08:25:56

问题


I have an input file with the following format:

[(1,1),(2,1)], 'add', 11
[(1,2),(1,3)], 'div', 2
[(3,1),(4,1),(3,2),(4,2)], 'times', 240
[(2,2),(2,3)], 'minus', 3
...

Each line is a tuple I want to create. How is it possible to convert each string line into a tuple?

For example, line string "[(1,1),(2,1)], 'add', 11" should be converted to a tuple: ([(1, 1), (2, 1)], 'add', 11).

So far, I tried:

tuples = []
for line in file:
    tuples.append((line,))

But I am getting a string conversion

 [("[(1,1),(2,1)], 'add', 11\n",), ("[(1,2),(1,3)], 'div', 2\n",), ("[(3,1),(4,1),(3,2),(4,2)], 'times', 240\n",), ("[(2,2),(2,3)], 'minus', 3",)]

回答1:


You may use ast.literal_eval as:

>>> import ast
>>> my_string = "[(1,1),(2,1)], 'add', 11"

>>> ast.literal_eval(my_string)
([(1, 1), (2, 1)], 'add', 11)

As per the ast.literal_eval(node_or_string) document:

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.



来源:https://stackoverflow.com/questions/41150857/convert-string-tuple-to-a-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!