因此,您希望将字符串拆分为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. |
+----------------------------+