Converting a string to a tuple in python

ε祈祈猫儿з 提交于 2019-12-01 11:19:51

All you need is ast.literal_eval:

>>> from ast import literal_eval
>>> tc = '(107, 189)'
>>> tc = literal_eval(tc)
>>> tc
(107, 189)
>>> type(tc)
<class 'tuple'>
>>> tc[0]
107
>>> type(tc[0])
<class 'int'>
>>>

From the docs:

ast.literal_eval(node_or_string)

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

Use ast.literal_eval():

>>> import ast
>>> tc='(107, 189)'
>>> tc_tuple = ast.literal_eval(tc)
>>> tc_tuple
(107, 189)
>>> tc_tuple[0]
107

You can use the builtin eval, which evaluates a Python expression:

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