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/

相关文章:

python - 如何使用 odbc 查询 Sybase IQ 服务器?

python - 如何在 python 中将\t 视为常规字符串

php - 将字符串转换为两个变量的最佳方法

java - 反转字符串的测试用例

python - 随机矩阵 : int() argument must be a string or a number, 不是 'tuple'

python - Django:名称 'csrf_token' 未定义

python - 如何处理python scikit NMF中的缺失值

python - 在 python 中遍历元组的语法错误

python - 为什么我会收到 TypeError : get() takes exactly 2 arguments (1 given)? Google App Engine

mysql - 创建 SQL 命令以从给定表中检索数据