converting string to tuple in python

前端 未结 5 1084
我寻月下人不归
我寻月下人不归 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 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')
    

提交回复
热议问题