gpt4 book ai didi

python - python中文本周围的动态边框

转载 作者:行者123 更新时间:2023-11-28 19:54:38 25 4
gpt4 key购买 nike

我需要输入一个句子并在该句子周围制作一个动态边框。边框需要有输入的宽度。当句子的长度高于给定的宽度时,必须打印一个新行并且边框的高度 必须改变。句子也必须在动态边框中居中

我已经试过了:

sentence = input()
width = int(input())

length_of_sentence = len(sentence)

print('+-' + '-'*(width) + '-+')

for letter in sentence:
print('| {0:^{1}} |'.format(letter, width - 4))

print('+-' + '-'*(width) + '-+')

但是随后每个带有新行的字母都被打印出来,这不是我需要的。

下面是一个很好的例子;

输入

sentence = "You are only young once, but you can stay immature indefinitely."
width = 26

输出

+----------------------------+
| You are only young once, b |
| ut you can stay immature i |
| ndefinitely. |
+----------------------------+

最佳答案

如果你想避免在中间断词,你也可以使用 textwrap.wrap:

from textwrap import wrap

sentence = input('Sentence: ')
width = int(input('Width: '))

print('+-' + '-' * width + '-+')

for line in wrap(sentence, width):
print('| {0:^{1}} |'.format(line, width))

print('+-' + '-'*(width) + '-+')

输出:

+----------------------------+
| You are only young once, |
| but you can stay immature |
| indefinitely. |
+----------------------------+

关于python - python中文本周围的动态边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35381065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com