Remove additional quotes from python list

后端 未结 2 516
一个人的身影
一个人的身影 2021-01-29 06:55

I have a list with below pattern and i want to get rid of \" which is present at the beginning and end of each sub list. I tried replace, strip but they are not the

相关标签:
2条回答
  • 2021-01-29 07:32

    This should do the trick:

    result = [[element.strip("'") for element in sub_list[0].split(', ')] for sub_list in lst]
    

    I'm assuming that the format for the string is "strings wrapped in single quotes separated by commas and spaces." Note that my code will probably not do the expected thing with input like [["'A comma here, changes the parsing', 'no comma here'"], ...]. (This would look to my code like three elements in a list, while I imagine you want to consider it two.)

    EDIT

    This is perhaps easier to understand as compared to the longer list comprehension:

    result = []
    for sub_list in lst:
        s = sub_list[0]
        result.append([element.strip("'") for element in s.split(', ')])
    
    0 讨论(0)
  • 2021-01-29 07:34

    You can use shlex.split after removing commas with replace:

    import shlex
    
    lst = [["'123', 'Name1', 'Status1'"], ["'234', 'Name2', 'Status2'"]]
    r = [shlex.split(x[0].replace(',', '')) for x in lst]
    # [['123', 'Name1', 'Status1'], ['234', 'Name2', 'Status2']]
    
    0 讨论(0)
提交回复
热议问题