converting string to tuple in python

 ̄綄美尐妖づ 提交于 2019-12-02 04:18:57

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. 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(",")). 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',)

A tuple of one has a trailing comma in the form (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('(mono)')
('(', 'm', 'o', 'n', 'o', ')')

Now it's a tuple.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!