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

David Rock david at graniteweb.com
Thu Aug 23 22:05:48 CEST 2012


* David Rock <david at graniteweb.com> [2012-08-23 15:03]:
> * Jared Nielsen <nielsen.jared at gmail.com> [2012-08-23 12:05]:
> > Hi all,
> > I'm new to programming and Python.
> > I want to write a script that takes a string input and breaks the string at
> > keywords then outputs the pieces on separate lines.
> 
> > 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.
> 
> While it's true that split() doesn't retain the separator, you still
> know what the separator is, right?  Why not do something like:
> 
> text = raw_input("Enter text: ") 
> sep = 'and'
> parts = text.split(sep)
> for i in parts[:-1]:
>     print i
>     print sep
> print [-1]

Oops, 
 print [-1] 
should have been 
 print parts[-1]

Hopefully you get the idea, though.

-- 
David Rock
david at graniteweb.com


More information about the Tutor mailing list