[Tutor] how to split/partition a string on keywords?
David Rock
david at graniteweb.com
Thu Aug 23 23:13:48 CEST 2012
* eryksun <eryksun at gmail.com> [2012-08-23 17:02]:
> On Thu, Aug 23, 2012 at 3:05 PM, Jared Nielsen <nielsen.jared at gmail.com> wrote:
> > 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.
>
> This is just for printing? You can use replace():
>
> >>> text = "Ham and cheese omelette with hasbrowns and coffee."
> >>> print text.replace(" and ", "\nand\n")
> Ham
> and
> cheese omelette with hasbrowns
> and
> coffee.
I like that :-)
If you aren't just printing, and want to use partition you will need to do some
recursion (I assume that's the expected use case for partition).
def repart(text):
parts = text.partition('and')
if parts[0] == text:
return (parts[0],)
else:
return parts[:-1] + repart(parts[-1])
if __name__ == '__main__':
text = "Ham and cheese omelette with hasbrowns and coffee."
parts = repart(text)
for part in parts:
print part.strip() # Clean up whitespace when printing.
--
David Rock
david at graniteweb.com
More information about the Tutor
mailing list