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

converting string to tuple in python

我有一个从 "('mono')" 等软件返回的字符串,我需要将字符串转换为元组。

我正在考虑使用 ast.literal_eval("('mono')"),但它说的是格式错误的字符串。

试试这个

a = ('mono')
print tuple(a)      # <-- you create a tuple from a sequence 
                    #(which is a string)
print tuple([a])    # <-- you create a tuple from a sequence 
                    #(which is a list containing a string)
print tuple(list(a))# <-- you create a tuple from a sequence 
                    #     (which you create from a string)
print (a,)# <-- you create a tuple containing the string
print (a)

输出:

('m', 'o', 'n', 'o')
('mono',)
('m', 'o', 'n', 'o')
('mono',)
mono

我假设所需的输出是一个只有一个字符串的元组:('mono',)

一个元组的尾部逗号形式为 (tup,)

a = '(mono)'
a = a[1:-1] # 'mono': note that the parenthesis are removed removed 
            # if they are inside the quotes they are treated as part of the string!
b = tuple([a]) 
b
> ('mono',)
# the final line converts the string to a list of length one, and then the list to a tuple

使用正则表达式如何?

In [1686]: x
Out[1686]: '(mono)'

In [1687]: tuple(re.findall(r'[\w]+', x))
Out[1687]: ('mono',)

In [1688]: x = '(mono), (tono), (us)'

In [1689]: tuple(re.findall(r'[\w]+', x))
Out[1689]: ('mono', 'tono', 'us')

In [1690]: x = '(mono, tonous)'

In [1691]: tuple(re.findall(r'[\w]+', x))
Out[1691]: ('mono', 'tonous')

由于您需要元组,因此在某些情况下您必须期望包含多个元素的列表。不幸的是,你没有给出超出琐碎 (mono) 之外的例子,所以我们不得不猜测。这是我的猜测:

"(mono)"
"(two,elements)"
"(even,more,elements)"

如果你的所有数据都是这样,通过拆分字符串(减去周围的括号)将其变成一个列表,然后调用元组构造函数。即使在单元素情况下也有效:

assert data[0] == "(" and data[-1] == ")"
elements = data[1:-1].split(",")
mytuple = tuple(elements)

或一步到位:elements = tuple(data[1:-1].split(","))。 如果您的数据不像我的示例,请编辑您的问题以提供更多详细信息。

将字符串转换为元组?只需申请 tuple:

>>> tuple('(mono)')
('(', 'm', 'o', 'n', 'o', ')')

现在是一个元组。