Skip to content Skip to sidebar Skip to footer

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 lis

Solution 1:

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

Solution 2:

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

Post a Comment for "Remove Additional Quotes From Python List"