converting string to tuple in python

前端 未结 5 1074
我寻月下人不归
我寻月下人不归 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: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.

提交回复
热议问题