Skip to main content
 首页 » 编程设计

python之如何在 python 中打印消息框

2025年05月04日24jirigala

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

请您参考如下方法:

这里有一个稍微详细的函数,用于打印带有可选标题和以最长行为中心的缩进的消息框:

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!                 ║ 
╚══════════════════════════════════════════════════════════╝