将字符串转换为列表时保留换行符,然后使用连接再次返回
Preserve line breaks when converting string to list and then back again with join
我在将以下字符串转换为列表并再次转换回来时遇到困难。我希望它保留行结尾,它使用 python 的三重括号 ("""
) 来封装莎士比亚的诗句。诗句是:
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 实例!
使用 splitlines()
instead of 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
如果你在 \n
:
上拆分,你可以用 split
达到同样的效果
>>> 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
不要使用 fullText.split()
。
这会导致您错过行尾(并且您不知道它们在哪里)。
我会拆分成一个行列表,然后在每个单词中拆分每一行。
我在将以下字符串转换为列表并再次转换回来时遇到困难。我希望它保留行结尾,它使用 python 的三重括号 ("""
) 来封装莎士比亚的诗句。诗句是:
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 实例!
使用 splitlines()
instead of split()
并使用 "\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
如果你在 \n
:
split
达到同样的效果
>>> 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
不要使用 fullText.split()
。
这会导致您错过行尾(并且您不知道它们在哪里)。
我会拆分成一个行列表,然后在每个单词中拆分每一行。