Drawing box around message

混江龙づ霸主 提交于 2019-12-02 14:53:11

I've stitched up a little piece of code which implements the boxed messages. To be honest it's not the nicest piece of code, but it does the job and hopefully will help you to do it yourself (and better). For that purpose I've decided not to include comment, so you have to think that through for yourself. Maybe not the best educational method, but let's try it anyway:]

Code on Github.

from math import ceil, floor

def boxed_msg(msg):
    lines = msg.split('\n')
    max_length = max([len(line) for line in lines])
    horizontal = '+' + '-' * (max_length + 2) + '+\n'
    res = horizontal
    for l in lines:
        res += format_line(l, max_length)
    res += horizontal
    return res.strip()

def format_line(line, max_length):
    half_dif = (max_length - len(line)) / 2 # in Python 3.x float division
    return '| ' + ' ' * ceil(half_dif) + line + ' ' * floor(half_dif) + ' |\n'

print(boxed_msg('first_line\nsecond_line\nthe_ultimate_longest_line'))
# +---------------------------+
# |         first_line        |
# |        second_line        |
# | the_ultimate_longest_line |
# +---------------------------+
def border_msg(msg):
    msg_lines=msg.split('\n')
    max_length=max([len(line) for line in msg_lines])
    count = max_length +2 

    dash = "*"*count 
    print("*%s*" %dash)

    for line in msg_lines:
        half_dif=(max_length-len(line))
        if half_dif==0:
            print("* %s *"%line)
        else:
            print("* %s "%line+' '*half_dif+'*')    

    print("*%s*"%dash)



border_msg('first_line\nsecond_line\nthe_ultimate_longest_line') # without print

Find out the length of your longest line N; (N+2) * '-' gives you the top and bottom borders. Before each line add a bar: '|'; pad each line with N - n spaces, where n is the length of that line. Append to each line a bar. Print in the correct order: top, line 1, line2, ..., line L, bottom.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!