2016-10-11 135 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)行的一半空格值即可。