在消息行周围画一个框

时间:2016-10-11 01:40:17

标签: python draw message box

我之前问过这个问题,但我收到的答案最终没有正常工作,所以我完全重新开始。我现在有更多开发的代码,但仍然无法弄清楚什么是错的,以及如何在一个像这样的框中包围和问候:

Example

最初的问题是:给定一条可能包含多行的消息,利用split()函数来识别各行,并使用我们在解决方案中学习的任何一种格式化方法来创建字符串,打印时,在消息的行周围绘制一个框,全部居中。该框使用边(|, - )上的垂直条和短划线,角(+)中的加号,并且在消息的最宽行的左侧和右侧始终有一列空格。所有线都居中。

这是我提出的代码。我认为它在正确的轨道上,但我遇到了错误,尤其是ver函数

def border_msg(msg):
    count=len(msg)
    for i in range(0,len(msg)):
        count+=1

    count = count
    dash="-"
    for i in range (0,count+1):
        dash+="-"
    h="{}{}{}".format("+",dash,"+")

    count=count+2

    ver="{}{:^'count'}{}".format("|",msg,"|")
    print (ver)

print(border_msg('a'))
print(border_msg("hello"))

2 个答案:

答案 0 :(得分:1)

要在字符串格式化中使用count值,您需要

ver = "{}{:^{}}{}".format("|", msg, count,"|")

或使用名称 - 因此它对您来说更具可读性

ver = "{a}{b:^{c}}{d}".format(a="|", b=msg, c=count, d="|")

但你也可以

ver = "|{a:^{b}}|".format(a=msg, b=count)

你可以在字符串中添加空格

ver = "| {} |".format(msg)

您的代码

def border_msg(msg):

    count = len(msg) + 2 # dash will need +2 too

    dash = "-"*count 

    print("+{}+".format(dash))

    print("| {} |".format(msg))

    print("+{}+".format(dash))


border_msg('a')     # without print
border_msg("hello") # without print

或没有print内部功能

def border_msg(msg):

    count = len(msg) + 2 # dash will need +2 too

    dash = "-"*count 

    return "+{dash}+\n| {msg} |\n+{dash}+".format(dash=dash,msg=msg)


print(border_msg('a'))     # with print
print(border_msg("hello")) # with print

答案 1 :(得分:1)

这里有一个可以解决问题的方法:

def box_lines(lines, width):
    topBottomRow = "+" + "-" * width + "+"
    middle = "\n".join("|" + x.ljust(width) + "|" for x in lines)
    return "{0}\n{1}\n{0}".format(topBottomRow, middle)

它期望正确分割的行:

def split_line(line, width):
    return [line[i:i+width] for i in range(0, len(line), width)]

def split_msg(msg, width):
    lines = msg.split("\n")
    split_lines = [split_line(line, width) for line in lines]
    return [item for sublist in split_lines for item in sublist] # flatten

box_linessplit_msg放在一起,我们得到:

def border_msg(msg, width):
    return(box_lines(split_msg(msg, width), width))

我们可以按如下方式使用它:

print(border_msg("""I'll always remember
The chill of November
The news of the fall
The sounds in the hall
The clock on the wall
Ticking away""", 20))

哪个输出

+--------------------+
|I'll always remember|
|The chill of Novembe|
|r                   |
|The news of the fall|
|The sounds in the ha|
|ll                  |
|The clock on the wal|
|l                   |
|Ticking away        |
+--------------------+