converting string to tuple in python

前端 未结 5 1073
我寻月下人不归
我寻月下人不归 2021-01-22 02:12

I have a string returnd from a software like \"(\'mono\')\" from that I needed to convert string to tuple .

that I was thinking using ast.literal_eval

相关标签:
5条回答
  • 2021-01-22 02:48

    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
    
    0 讨论(0)
  • 2021-01-22 02:54

    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.

    0 讨论(0)
  • 2021-01-22 03:04

    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
    
    0 讨论(0)
  • 2021-01-22 03:10

    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')
    
    0 讨论(0)
  • 2021-01-22 03:10

    Convert string to tuple? Just apply tuple:

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

    Now it's a tuple.

    0 讨论(0)
提交回复
热议问题