converting string to tuple in python

前端 未结 5 1085
我寻月下人不归
我寻月下人不归 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条回答
  •  旧时难觅i
    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
    

提交回复
热议问题