Python List comprehension: Single string to list
Question: I'm struggling with list comprehensions.

Basically I have a simple string:

    
    
    string =  "['a','b','c','d']"
    

Note, that the brackets,commas and quotation marks are part of the string.
What I need is a `list1` with a,b,c,d as elements (so i need to get rid of the
quotation marks, the commas and brackets.)

for entry in string:

    
    
    list1 = [x.lstrip(" ' ") for x in string.split(',')]
    list2 = [x.strip(" ' ") for x in list1]
    

This does not work at all. list1 gets created without the beginning `"'"`, but
when I try to print out list2 the quotations are there again. I did not even
start dealing with the brackets. Is there a nice way to get my list?


Answer: If your string is already built as a list object but with quotation marks as
you stated:

    
    
    string =  "['a','b','c','d']"
    

You can simply make

    
    
    exec('list1='+string)
    

* * *

As an alternative, you can remove everything that is not commas, and end up
with

    
    
    string = "a,b,c,d"
    

For instance

    
    
    import re
    string = re.sub(r"[^\w,]", "", string)
    

And then you use

    
    
    >>> list1 = string.split(',')
    >>> list1
    ['a','b','c','d']
    

