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

标签 python string tuples

好的,我有这个字符串

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/

相关文章:

java - 比较SQLite for Java中包含重音的字符串不起作用

python - 从 Python 中的字符串中删除不需要的字符

python - 在我的输入框中添加字母?

python - Python 中的指数分布

java - 评估后缀表达式,例如

python-3.x - 如何在 Python 中将元组中的元素(字符串)转换为整数

c# - 如何根据另一个项目的值获取元组列表中一个项目的值?

python - 在 Python 中,in 运算符是如何实现的?它是否使用迭代器的 next() 方法?

python脚本在后台运行时看到回溯

c++ - 可变参数模板 initilizer_list 技巧