在不删除现有换行符的情况下使长字符串换行的方法?

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

我正在为我的 python 课程做一个期末项目,并选择制作一个拼写库,我可以在玩 DnD 时使用它。 (是的,我知道那里已经有很多了,但我想要我自己喜欢的方式)。

当我的程序打印拼写信息时,现在它会将文本包装在单词中间:

Spell: Acid Splash

Output:

Source: Player's Handbook

Conjuration cantrip

Casting Time: 1 action
Range: 60 feet
Components: V, S
Duration: Instantaneous

You hurl a bubble of acid. Choose one creature you can see within range, or choose two creatures you can see within range that are within 5 feet of e
ach other. A target must succeed on a Dexterity saving throw or take 1d6 acid damage.

At Higher Levels. This spell’s damage increases by 1d6 when you reach 5th level (2d6), 11th level (3d6), and 17th level (4d6).

Spell Lists. Artificer, Sorcerer, Wizard

在这个例子中,它在“每个”的中间分开,因为这是我终端边缘的词,但其他咒语当然还有其他被切断的词。

我希望它在单词之前或之后换行。

我已经尝试过 textwrapper,但这只会让它变得不稳定,因为它没有考虑现有的换行符。我在本网站的其他查询中找到的其他解决方案也会删除换行符。

python word-wrap
1个回答
0
投票

自己做这个并不难。在换行符上拆分以从您的文本中获取行。然后将其分解成单词。跟踪打印的单词长度。如果超过指定宽度,则打印一个换行符。然后打印单词后跟一个空格。

在每一行的末尾,打印一个换行符。

text = """Spell: Acid Splash

Output:

Source: Player's Handbook

Conjuration cantrip

Casting Time: 1 action
Range: 60 feet
Components: V, S
Duration: Instantaneous

You hurl a bubble of acid. Choose one creature you can see within range, or choose two creatures you can see within range that are within 5 feet of each other. A target must succeed on a Dexterity saving throw or take 1d6 acid damage.

At Higher Levels. This spell’s damage increases by 1d6 when you reach 5th level (2d6), 11th level (3d6), and 17th level (4d6).

Spell Lists. Artificer, Sorcerer, Wizard"""

# With a line length of 40 characters

for line in text.split('\n'):
  words = line.split()
  count = 0
  for word in words:
    count += len(word) + 1
    if count > 40:
      print()
      count = 0
    print(f"{word} ", end='')
  print()
© www.soinside.com 2019 - 2024. All rights reserved.