splitting a long string into a list

Peter Otten __peter__ at web.de
Tue Nov 28 02:51:02 EST 2006


ronrsr wrote:

> still having a heckuva time with this.

You don't seem to get it.

> here's where it stand - the split function doesn't seem to work the way
> i expect it to.
> 
> 
> longkw1,type(longkw):   Agricultural subsidies; Foreign
> aid;Agriculture; Sustainable Agriculture - Support; Organic
> Agriculture; Pesticides, US, Childhood Development, Birth Defects;
> <type 'list'> 1
> 
> longkw.replace(',',';')

>>> sample = "eat, drink; man, woman"
>>> sample.replace(";", ",")
'eat, drink, man, woman'
>>> sample
'eat, drink; man, woman'

Aha, Python doesn't replace in place, it creates a new string instead.

> Agricultural subsidies; Foreign aid;Agriculture; Sustainable
> Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood
> Development
> 
> 
>  kw = longkw.split("; ,")    #kw is now a list of len 1

>>> sample = "eat+-drink+man-woman"
>>> sample.split("+-")
['eat', 'drink+man-woman']
>>> sample.split("+")
['eat', '-drink', 'man-woman']

Aha, Python interprets the complete split() argument as the delimiter, not
each of its characters.

Do you think you can combine these two findings to make your code work? You
will have to replace() first and then split().

Peter



More information about the Python-list mailing list