[Tutor] how to split/partition a string on keywords?

Alan Gauld alan.gauld at btinternet.com
Thu Aug 23 23:25:40 CEST 2012


On 23/08/12 20:05, Jared Nielsen wrote:

> But split() doesn't retain the separator and partition() retains the
> white space and returns a 3-tuple which I'll have to figure out how to
> rejoin nor does it partition on subsequent instances of the separator.

David has shown one option for using split(), there are several others too.

To use partition just call it repeatedly until the last string is empty. 
As ever the >>> prompt is your friend:

 >>> st = 'here we go and there you are and we all go roundabout'
 >>> h,s,t = st.partition(' and')
 >>> results = [h,s]
 >>> while t:
...    h,s,t = t.partition(s)
...    results += [h,s]
...
 >>> results
['here we go', ' and', ' there you are', ' and', ' we all go 
roundabout', '']
 >>>


It leaves an empty string at the end that can easily be trimmed off by 
slicing:

results = results[:-1]

Finally you can also find a solution using regular expressions, but they 
shouldn't be needed for something like this.

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



More information about the Tutor mailing list