将以下字符串转换为列表并再次返回时,我遇到了困难。我希望它保留行结尾,使用蟒蛇三重括号("""
)来封装莎士比亚的一节经文。这节经文是:
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"""
使用print fullText
时,结果与预期一致。但是,当我将其转换为包含fullText.split()
的列表并再次使用" ".join(fullText)
时,结果是一行,其中所有单词都在一行上。
我知道这是正常行为,但我无法弄清楚是否有任何方法可以保留行结尾。
显然我正在建立一个莎士比亚测验,要求用户用正确的单词替换所有QUIZ实例!
答案 0 :(得分:3)
使用 splitlines()
代替 split()
,并使用"\n".join()
加入新行(如@PM 2Ring建议):
>>> 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
如果您在split
上拆分,则可以使用\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
答案 1 :(得分:-1)
不要使用fullText.split()
。
这会导致你错过你的结尾(你不知道他们在哪里)。
我会分成一个行列表,然后分割每个单词中的每一行。