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

David Rock david at graniteweb.com
Thu Aug 23 22:03:39 CEST 2012


* 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]

You might also want to consider stripping whitespace in the individual
list items, too.

-- 
David Rock
david at graniteweb.com


More information about the Tutor mailing list