2016-02-13 34 views
2

我需要輸入一個句子並在該句子周圍製作動態邊框。邊框需要有一個輸入的寬度。當句子的長度高於給定寬度時,必須打印新行並且邊界必須在高度處更改。這句話也有在動態邊界圍繞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.  | 
+----------------------------+ 
+0

我知道有已經發布解決此主題的問題,但他們沒有覆蓋動態輸入。 –

+1

看看[每隔第n個字符分割python字符串?](http://stackoverflow.com/questions/9475241/split-python-string-every-nth-character)。這應該讓你開始。 –

+0

@DriesCoppens:那又怎麼樣?它不應該有所作爲。 –

回答

3

因此,而不是做一個字母明智輸入,你會希望將字符串分割成chunks of width letters。以接受的答案:

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.   | 
+----------------------------+ 
+0

工程像一個魅力,但有一個問題,我沒有提到。如果寬度高於句子的長度,則寬度等於句子的寬度,因此您不會創建巨大的動態邊框。 –

+1

簡單,只需添加一行'width = min(width,len(句子))' –

0
import math 

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

length_of_sentence = len(sentence) 

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

i = 0 
lines = int(math.ceil(length_of_sentence/float(width))) 
for l in xrange(lines): 
    line = sentence[i:i+width] 
    if len(line) < width: 
     padding = (width - len(line))/2 
     line = padding*' ' + line + padding*' ' 
    print('| {0} |'.format(line)) 
    i += width 

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

我會用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.  | 
+----------------------------+ 
5

您也可以使用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.  | 
+----------------------------+