如何在python中打印消息框

时间:2016-10-11 01:15:27

标签: string python-3.x

我正在尝试在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|', '+-+'].

3 个答案:

答案 0 :(得分:4)

当您使用列表理解时,您将输出作为列表,如输出所示, 要查看打印result

所需的换行符

此外,您正在使用columns乘以-,这对于所有字符串只有一个。 将其更改为“行'

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

<强>输出

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

答案 1 :(得分:1)

如果您只想打印一行,上面的答案很好,但是,它们会分解多行。如果要打印多行,可以使用以下内容:

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)行的一半空格值。

答案 2 :(得分:0)

这是一个精心制作的功能,用于打印带有可选标题和缩进的消息框,该消息框以最长的行为中心:

def print_msg_box(msg, indent=1, width=None, title=None):
    """Print message-box with optional title."""
    lines = msg.split('\n')
    space = " " * indent
    if not width:
        width = max(map(len, lines))
    box = f'╔{"═" * (width + indent * 2)}╗\n'  # upper_border
    if title:
        box += f'║{space}{title:<{width}}{space}║\n'  # title
        box += f'║{space}{"-" * len(title):<{width}}{space}║\n'  # underscore
    box += ''.join([f'║{space}{line:<{width}}{space}║\n' for line in lines])
    box += f'╚{"═" * (width + indent * 2)}╝'  # lower_border
    print(box)

演示:

print_msg_box('\n~ PYTHON ~\n')
╔════════════╗
║            ║
║ ~ PYTHON ~ ║
║            ║
╚════════════╝
print_msg_box('\n~ PYTHON ~\n', indent=10)
╔══════════════════════════════╗
║                              ║
║          ~ PYTHON ~          ║
║                              ║
╚══════════════════════════════╝
print_msg_box('\n~ PYTHON ~\n', indent=10, width=20)
╔════════════════════════════════════════╗
║                                        ║
║          ~ PYTHON ~                    ║
║                                        ║
╚════════════════════════════════════════╝
msg = "And I thought to myself,\n" \
      "'a little fermented curd will do the trick',\n" \
      "so, I curtailed my Walpoling activites, sallied forth,\n" \
      "and infiltrated your place of purveyance to negotiate\n" \
      "the vending of some cheesy comestibles!"

print_msg_box(msg=msg, indent=2, title='In a nutshell:')
╔══════════════════════════════════════════════════════════╗
║  In a nutshell:                                          ║
║  --------------                                          ║
║  And I thought to myself,                                ║
║  'a little fermented curd will do the trick',            ║
║  so, I curtailed my Walpoling activites, sallied forth,  ║
║  and infiltrated your place of purveyance to negotiate   ║
║  the vending of some cheesy comestibles!                 ║
╚══════════════════════════════════════════════════════════╝