python中文本周围的动态边框
我需要输入一个句子,并在该句子周围创建一个动态边框。边框需要有一个输入的宽度。当句子的长度大于给定的宽度时,必须打印一行新行,并且必须在高度中更改边框。句子也必须以动态边界为中心 我已经试过了:python中文本周围的动态边框,python,Python,我需要输入一个句子,并在该句子周围创建一个动态边框。边框需要有一个输入的宽度。当句子的长度大于给定的宽度时,必须打印一行新行,并且必须在高度中更改边框。句子也必须以动态边界为中心 我已经试过了: sentence = input() width = int(input()) length_of_sentence = len(sentence) print('+-' + '-'*(width) + '-+') for letter in sentence: print('| {0:^
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. |
+----------------------------+
因此,您不需要按字母顺序输入,而是希望将字符串拆分为。采纳公认的答案:
def chunkstring(string, length):
return (string[0+i:length+i] for i in range(0, len(string), length))
sentence = input('Sentence: ')
width = int(input('Width: '))
print('+-' + '-' * width + '-+')
for line in chunkstring(sentence, width):
print('| {0:^{1}} |'.format(line, width))
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. |
+----------------------------+
导入数学
句子=输入()
宽度=int(输入())
句子长度=len(句子)
打印('+-'+'-'*(宽度)+'-+'))
i=0
lines=int(math.ceil(句子长度/浮点数(宽度)))
对于X范围内的l(行):
行=句子[i:i+宽度]
如果长度(线)<宽度:
填充=(宽度-长度(线))/2
行=填充*“”+行+填充*“”
打印(“|{0}|”格式(行))
i+=宽度
打印('+-'+'-'*(宽度)+'-+'))
我将使用PrettyTable模块完成这项任务-它将“很好地”打印:
import prettytable as pt
sentence = "You are only young once, but you can stay immature indefinitely."
width = 26
t = pt.PrettyTable()
t.field_names = ['output']
[t.add_row([sentence[i:i + width]]) for i in range(0, len(sentence), width)]
print(t)
输出:
+----------------------------+
| output |
+----------------------------+
| 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. |
+----------------------------+
我知道已经有关于这个主题的问题发布了,但它们不包括动态输入。请看。这应该让你开始了。@Driescopens:那又怎样?这不应该有什么区别。它很有魅力,但有一个问题我没有提到。如果宽度大于句子的长度,则宽度等于句子的宽度,因此您不会创建巨大的动态边框。简单地说,只需在那里添加一行
width=min(width,len(句子))
+----------------------------+
| You are only young once, |
| but you can stay immature |
| indefinitely. |
+----------------------------+