Search code examples
pythonfunctionmethodssplitsentence

How do I define a function to split a string into separate lines?


Say, the string looks like:

I like pie. You like apples. We like oranges.

How would I define a function, called format_poem() that would essentially take any input with a paragraph like the one above and give us each sentence in a separate line?

I'm sure it lies in the period after each sentence but being a noob, I can't wrap my head around it. Does this also use the .split() method?

Thanks for your help.


Solution

  • Replace the periods with the character for a new line (which is almost universally \n) using .replace()

    def format_poem(paragraph):
        return paragraph.replace('. ','\n')