简体   繁体   中英

Remove additional quotes from python list

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 attribute of list and therefore gives AttributeError .

lst = [["'123', 'Name1', 'Status1'"], ["'234', 'Name2', 'Status2'"]]

I am looking for below as my final result:

lst = [['123', 'Name1', 'Status1'], ['234', 'Name2', 'Status2']]

Please suggest how to remove double quotes from each sub list.

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']]

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(', ')])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM