好的,我有这个字符串
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.