简体   繁体   English

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

[英]converting string to tuple in python

I have a string returnd from a software like "('mono')" from that I needed to convert string to tuple . 我有一个从类似"('mono')"类的软件返回的字符串,我需要将字符串转换为元组。

that I was thinking using ast.literal_eval("('mono')") but it is saying malformed string. 我当时在想使用ast.literal_eval("('mono')")但它说的是格式错误的字符串。

Since you want tuples, you must expect lists of more than element in some cases. 由于需要元组,因此在某些情况下,您必须期望包含不止元素的列表。 Unfortunately you don't give examples beyond the trivial (mono) , so we have to guess. 不幸的是,您没有给出琐碎的示例(mono) ,因此我们不得不猜测。 Here's my guess: 这是我的猜测:

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

If all your data looks like this, turn it into a list by splitting the string (minus the surrounding parens), then call the tuple constructor. 如果您的所有数据都是这样,请通过分割字符串(减去周围的括号)将其转换为列表,然后调用元组构造函数。 Works even in the single-element case: 即使在单元素情况下也可以使用:

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

Or in one step: elements = tuple(data[1:-1].split(",")) . 或者一步: elements = tuple(data[1:-1].split(",")) If your data doesn't look like my examples, edit your question to provide more details. 如果您的数据看起来并不像我的例子,编辑你的问题 ,以提供更多的细节。

How about using regular expressions ? 使用正则表达式怎么样?

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')

Try to this 试试这个

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)

Output : 输出:

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

I assume that the desired output is a tuple with a single string: ('mono',) 我假设所需的输出是带有单个字符串的元组:('mono',)

A tuple of one has a trailing comma in the form (tup,) 一个元组的末尾逗号为(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

Convert string to tuple? 将字符串转换为元组? Just apply tuple : 只需应用tuple

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

Now it's a tuple. 现在是一个元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM