Search code examples
pythonstringjoinsplitline-breaks

Preserve line breaks when converting string to list and then back again with join


I'm facing difficulties when converting the below string to a list and back again. I want it to preserve the line endings, which uses pythons triple parenthesis (""") to encapsulate a Shakespearean verse. The verse is:

fullText= """Hamlet's Soliloquay - Act III Scene i

To QUIZ or not to Be, that is the QUIZ:
Whether tis nobler in the QUIZ to suffer
The slings and arrows of outrageous QUIZ,
Or to take Arms against a QUIZ of troubles,
And by opposing end them: to die, to QUIZ"""

When using print fullText the result is as expected. But when I convert this to a list with fullText.split() and back again with " ".join(fullText) the result is a string with all words on one line.

I know this is normal behaviour, but I can't figure out if there is any way to preserve the line endings.

Obviously I am building a shakespeare quiz asking the user to replace all instances of QUIZ with the correct word!


Solution

  • Use splitlines() instead of split() and join on newlines (as @PM 2Ring suggested) with "\n".join():

    >>> print "\n".join(fullText.splitlines())
    Hamlet's Soliloquay - Act III Scene i
    
    To QUIZ or not to Be, that is the QUIZ:
    Whether tis nobler in the QUIZ to suffer
    The slings and arrows of outrageous QUIZ,
    Or to take Arms against a QUIZ of troubles,
    And by opposing end them: to die, to QUIZ
    

    You can achieve the same exact thing with split if you split on \n:

    >>> print "\n".join(fullText.split('\n'))
    Hamlet's Soliloquay - Act III Scene i
    
    To QUIZ or not to Be, that is the QUIZ:
    Whether tis nobler in the QUIZ to suffer
    The slings and arrows of outrageous QUIZ,
    Or to take Arms against a QUIZ of troubles,
    And by opposing end them: to die, to QUIZ