我写的字符串很长。为了更容易阅读,我想将文本换行为多行。这是怎么做到的?
[这个答案一般适用于 Python,并不特定于 IDLE。]
对于输入没有嵌入换行符的长字符串,您可以输入多行字符串,然后删除换行符。但是,如果您希望行在逗号和句点之后以空格结尾,则您将看不到它们,并且如果您从代码中删除行结束空格,它们也会消失。 (这是 CPython stdlib 代码所必需的。)
另一种方法是使用 Python 的 字符串文字连接 功能。空格由行结束引号保护,并且可以添加注释。 (请参阅另一个示例的链接。)
stories = {
'John' : "One day John went to the store to buy a game. " # the lead
"The name of the game was Super Blaster. " # the hint
"On the way to the store, John was blasted by a purple ray. "
"The ray of purple light, mixed with super neutrinos, "
"came from a alien spaceship hovering above."
}
import textwrap
print('\n'.join(textwrap.wrap(stories['John'])))
# prints
One day John went to the store to buy a game. The name of the game
was Super Blaster. On the way to the store, John was blasted by a
purple ray. The ray of purple light, mixed with super neutrinos, came
from a alien spaceship hovering above.
对于仍在寻找答案的人:
希望有帮助。