Python 中的文本换行

问题描述 投票:0回答:2

我写的字符串很长。为了更容易阅读,我想将文本换行为多行。这是怎么做到的?

python word-wrap
2个回答
0
投票

[这个答案一般适用于 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.

0
投票

对于仍在寻找答案的人:

  1. 点击左上角的IDLE
  2. 选择设置
  3. 选择按键
  4. 找到“换行和缩进”
  5. 选择获取新选择密钥
  6. 输入您选择的快捷键

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.