在python中将字符串转换为元组

好的,我有这个字符串

tc='(107, 189)'

我需要它成为一个元组,所以我可以一次拨打每个号码.

print(tc[0]) #needs to output 107

先感谢您!

解决方法:

你需要的只是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'>
>>>

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.

上一篇:在mysql中使用元组比较是否有效?


下一篇:将Python 2D矩阵/列表转换为表格