How best to convert a string "list" to a python list
Nobody
nobody at nowhere.com
Sat May 14 04:41:20 EDT 2011
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.
More information about the Python-list
mailing list