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

John Posner jjposner at optimum.net
Fri May 13 23:47:49 EDT 2011


On 5/13/2011 3:38 PM, 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,

No big deal that you weren't aware of the split() method for strings.
Since you asked for pointers, here are some notes on your code -- which
is just fine, overall!

> x = "red;blue;green;yellow" ## string of semi-colon delimited colors
>
> color_list = []
> ## sc = semi-colon
>
> while x.find(";") <> -1:
>     sc_pos = x.find(";")
>     current_color = x[0:sc_pos] ## color w/o sc
>     current_color_sc = x[0:sc_pos+1] ## color with sc

You don't really need the variable "current_color_sc", since you use it
only once. For example, your invocation of replace() could look like this:

  x = x.replace(current_color + ";", "")

But if you really want the extra variable, the following definition is
clearer (and also avoids a slice operation):

    current_color_sc = current_color + ";"


>     color_list.append(current_color) ## append color to list
>     x = x.replace(current_color_sc, "") ## remove color and sc from string

Here's another reason why you don't need the variable
"current_color_sc": instead of using replace(), why not just chop off
the first N characters of the string:

 x = x[len(current_color)+1:]

(The "+1" takes care of the semicolon.)


>     print current_color
>     print color_list
>     print x + "\n"
>
> color_list.append(x) # append last color left in x (no sc at end of >
string)

Does that last append(), outside the loop, offend you?  You can get rid
of it by modifying the original string:

   x = "red;blue;green;yellow"
   x += ";"

Now, the final component of the string is no longer a special case, but
is terminated by ";" -- just like all the other components.

HTH,
John




More information about the Python-list mailing list