邮件周围的绘图框

2024-04-19 07:00:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理这个Python任务,我搞不懂。它是3个函数中的最后一个,前2个比这个更容易编程。说明如下 “给定一条可能包含多行的消息,使用split()函数来标识各个行,而format()函数则在消息行周围画一个框,所有行都居中。Box在侧面使用竖线和破折号(|,-),+在角(+),并且消息最宽行的左右两侧始终有一列空格。”

此函数需要执行的操作的一些示例:

测试:border_msg('a')=='+--+\n | a |\n+--+\n'

测试:border_msg('hello')=='+---+\n | hello | \n+------+\n'

测试:border\u msg(“嗨!\你怎么样?\安全驾驶!)=='+-------------+\n |嗨!|\你好吗?|\安全驾驶!|\n+----------------+\n'

我认为它需要打印上面的测试,以便中间的单词在顶部和底部被“+——+”包围,在侧面用“|”包围。在

这是我目前掌握的密码。我不知道从这里我会去哪里。在

def border_msg(msg):
    border_msg.split("\n")
    '%s'.format(msg)
    return border_msg(msg)
    print border_msg(msg)

Tags: 函数boxformat消息示例hello编程msg
3条回答

我已经缝合了一段实现装箱消息的代码。老实说,这不是最好的一段代码,但它确实起到了作用,希望能帮助您自己(甚至更好地)完成它。出于这个目的,我决定不写评论,所以你得自己考虑一下。也许不是最好的教育方法,但我们还是试试看吧:]

^{}上编码。在

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 |
# +             -+

找出最长一行的长度;(N+2) * '-'给出了上下边界。在每行之前添加一个条:“|”;用N - n空格填充每一行,其中n是该行的长度。在每一行附加一个条。按正确的顺序打印:顶部,第1行,第2行,…,第L行,底部。在

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

相关问题 更多 >