2016-10-11 133 views
0

我試圖在python中創建的框中打印出一條消息,但不是直接打印,而是水平打印。如何在python中打印消息框

def border_msg(msg): 
    row = len(msg) 
    columns = len(msg[0]) 
    h = ''.join(['+'] + ['-' *columns] + ['+']) 
    result = [h] + ["|%s|" % row for row in msg] + [h] 
    return result 

預期結果

border_msg('hello') 

+-------+ 
| hello | 
+-------+ 

但得到

['+-+', '|h|', '|e|', '|l|', '|l|', '|o|', '+-+']. 

回答

2

當您使用列表中理解你得到的輸出列表,通過你的輸出所看到, 看您需要打印的新行字符result

而且您還在使用columns來乘以-,這是所有字符串中唯一的一個。 將其更改爲'行」

def border_msg(msg): 
    row = len(msg) 
    h = ''.join(['+'] + ['-' *row] + ['+']) 
    result= h + '\n'"|"+msg+"|"'\n' + h 
    print(result) 

輸出

>>> border_msg('hello') 
+-----+ 
|hello| 
+-----+ 
>>> 
+0

有沒有辦法做到這一點,而不使用連接? – struggling

+0

@struggling''+'+' - '* row +'+'' – user2728397

0

以上答案是好的,如果你只想打印一條線,然而,他們打破了多行。如果要打印多行,你可以使用以下命令:

def border_msg(msg): 
    l_padding = 2 
    r_padding = 4 

    msg_list = msg.split('\n') 
    h_len = max([len(m) for m in msg]) + sum(l_padding, r_padding) 
    top_bottom = ''.join(['+'] + ['-' * h_len] + ['+']) 
    result = top_bottom 

    for m in msg_list: 
     spaces = h_len - len(m) 
     l_spaces = ' ' * l_padding 
     r_spaces = ' ' * (spaces - l_padding) 
     result += '\n' + '|' + l_spaces + m + r_spaces + '|\n' 

    result += top_bottom 
    return result 

這將打印周圍多行字符串與指定的填充值確定框中的文本的位置左對齊的盒子。相應地調整。

如果要將文本居中,只需使用一個填充值並交叉管道之間spaces = h_len - len(m)行的一半空格值即可。