Create a box with text in center

2019-09-19 07:00发布

问题:

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:

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