[Tutor] Extracting the list from a string

Alan Gauld alan.gauld at btinternet.com
Thu Jul 12 10:54:14 CEST 2012


On 11/07/12 09:48, kala Vinay wrote:

>         say i have a string s="['a','b']" and i want to get a list
> object from this string s ie l=['a','b']

It depends on how complex your string is and how much you want to put in 
the list. If you just want to convert the entire expression into a 
Python value then Steven's use of ast is simplest.

If you want to extract elements out of the string, like the letters in 
your example then you could use a list comprehension:

L = [c for c in s if c.isalpha()]

Or for more complex scenarios you can supply a list of valid values:

vowels = 'aeiou'
L = [c for c in s if c in vowels]

Or for even more complex rules you could supply any arbitrary function:

L = [c for c in s if myfunc(c)]

Other options include using a regular expression.
It all depends on exactly what you want to put in your list.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list