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

ast.literal_eval:

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

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -