Create a box with text in center

2019-09-19 06:07发布

I want to draw a box around my message. The result to be like this:

 # # # # # # # # # # # # # # # # # # # # # # # # #
 #                                               #
 #                   Message                     #
 #                                               #
 # # # # # # # # # # # # # # # # # # # # # # # # #

The box must be resized if the message is longer or shorter. I tried a method, but I can't figure it out to solve it further.

total_rows = 5
total_cols = 25
Matrix = [[' ' for x in range(total_cols)] for y in range(total_rows)]

def LBoder():
    for i in range(total_rows):
        Matrix[i][0] = '#'

def TBorder():
    for i in range(total_cols - 1):
        Matrix[0][i] = '#'

def BBorder():
    for i in range(total_cols - 1):
        Matrix[total_rows - 1][i] = '#'

def RBorder():
    for i in range(total_rows):
        Matrix[i][total_cols - 1] = '#'

def message(msg):
    Matrix[2][1] = msg

def output():
    count = len('Test')
    message('Test')

    TBorder()
    LBoder()
    RBorder()
    BBorder()

    for row in Matrix:
        orow = ''
        for x in row:
            orow += " " + str(x)
        print orow

output()

1条回答
何必那么认真
2楼-- · 2019-09-19 06:46

Just build each line separately:

emptyspace = "                   "
lempty = len(emptyspace)
addS = "Message"
news = "#" + emptyspace + addS + emptyspace + "#"
lnew = len(news)

edge = "# "
mid = "# "
for i in range((lnew / 2 - 1)):
    edge += "# "
    mid += "  "
edge += "#"
mid += "#"

print edge
print mid
print news
print mid
print edge
查看更多
登录 后发表回答