Reputation: 27
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!
Upvotes: 0
Views: 1840
Reputation: 160657
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
Upvotes: 3
Reputation: 5866
Don't use fullText.split()
.
That's causing you to miss your ending of lines (and you won't know where they are).
I'd split into a list of lines, and THEN split each line in each word.
Upvotes: -1