How best to convert a string "list" to a python list

Terry Reedy tjreedy at udel.edu
Sat May 14 15:59:33 EDT 2011


On 5/14/2011 4:41 AM, Nobody wrote:
> On Fri, 13 May 2011 10:15:29 -0700, noydb wrote:
>
>> I want some code to take the items in a semi-colon-delimted string "list"
>> and places each in a python list.  I came up with below.  In the name of
>> learning how to do things properly, do you experts have a better way of
>> doing it?
>
>> x = "red;blue;green;yellow" ## string of semi-colon delimited colors
>
> Provided that a semicolon is *always* a delimiter, just use the .split()
> method:
>
> 	color_list = x.split(";")
>
> For more complex formats, where there are quote and/or escape characters
> which allow the delimiter to occur as part of an item, you typically need
> to use a regular expression to match everything up to the next delimiter,
> and do this in a loop to extract the individual items.

Or, for some formats, use the cvs module.


-- 
Terry Jan Reedy




More information about the Python-list mailing list