Convert string representation of list to list in Python -
i wondering simplest way convert string
list following list
:
x = u'[ "a","b","c" , " d"]'
even in case user puts spaces in between commas, , spaces inside of quotes. need handle to:
x = ["a", "b", "c", "d"]
in python.
i know can strip spaces strip()
, split()
using split operator , check non alphabets. code getting kludgy. there quick function 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() n in x] >>> x ['a', 'b', 'c', 'd']
safely evaluate expression node or string containing python expression. string or node provided may consist of following python literal structures: strings, numbers, tuples, lists, dicts, booleans, , none.
Comments
Post a Comment