I was wondering what the simplest way is to convert a
string list like the following to a
x = u'[ "A","B","C" , " D"]'
Even in case user puts spaces in between the commas, and spaces inside of the quotes. I need to handle that as well to:
x = ["A", "B", "C", "D"]
I know I can strip spaces with
split() using the split operator and check for non alphabets. But the code was getting very kludgy. Is there a quick function that I'm not aware of?
>>> import ast >>> x = u'[ "A","B","C" , " D"]' >>> x = ast.literal_eval(x) >>> x ['A', 'B', 'C', ' D'] >>> x = [n.strip() for n in x] >>> x ['A', 'B', 'C', 'D']
With ast.literal_eval, you can safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
eval is dangerous - you shouldn't execute user input.
If you have 2.6 or newer, use ast instead of eval:
>>> import ast >>> ast.literal_eval('["A","B" ,"C" ," D"]') ["A", "B", "C", " D"]
Once you have that,
strip the strings.
If you're on an older version of Python, you can get very close to what you want with a simple regular expression:
>>> x='[ "A", " B", "C","D "]' >>> re.findall(r'"\s*([^"]*?)\s*"', x) ['A', 'B', 'C', 'D']
This isn't as good as the ast solution, for example it doesn't correctly handle escaped quotes in strings. But it's simple, doesn't involve a dangerous eval, and might be good enough for your purpose if you're on an older Python without ast.