python中文本周围的动态边框
问题内容:
我需要输入一个句子,并在该句子周围添加动态边框。边框需要具有输入的宽度。当句子的长度大于给定的宽度时,必须打印新行,并且边框的 高度
必须改变。句子也必须以动态边界为中心
我已经尝试过了:
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. |
+----------------------------+
问题答案:
因此,您希望将字符串拆分为width
字母块,而不是按字母输入。采取公认的答案:
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. |
+----------------------------+