好的,我有这个字符串
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.
关于python - 在python中将字符串转换为元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173916/