如何在 python 中使用用户输入和字符串操作制作框架框?

How to make framed box using user input and string manipulation in python?

这是我的资料:

frame = input("Enter frame character ==> ")
print(frame)
height = int(input("Height of box ==> "))
print(height)
width = int(input("Width of box ==> "))
print(width)
print("Box:")
print(frame*width)
print(frame + " "*height + frame)
space = int((width - height)/2)
print(frame + (" "* space) + "{}X{}".format(width,height) + (" "* space) + frame)
print(frame + " "*height + frame)
print(frame*width)

我应该编写一个程序,要求用户输入框架字符,然后是框架框的高度和宽度。然后,输出一个给定大小的框,由给定的字符框起来。此外,我必须输出框内水平和垂直居中的框的尺寸。我需要先把盒子的尺寸放在一个字符串中,然后用它的长度来计算 包含尺寸的线应该有多长。我需要能够打印各种不同高度和宽度的盒子,所以如果我输入 11 的宽度和 8 的高度,我需要 11x8 的盒子。我的现在只给了一个7x5的盒子,我卡住了。

示例: enter image description here

我不能在此作业中使用任何 if 语句或循环,只能使用字符串操作。我不确定如何以这种方式这样做。任何帮助或提示将不胜感激,谢谢!

修改为不包含任何 if(但使用 assert 以确保一些最小宽度和高度):

def box_str(w, h, c='.'):
    assert len(c) == 1, "c must be single char"
    assert w >= 5, "minimum width: 5"
    assert h >= 3, "minimum height: 3"
    dim = f'{w}x{h}'
    banner = c * w
    pad = ' ' * (w - 2)
    row = c + pad + c
    nleft = len(pad) - len(dim)
    nright = nleft // 2
    nleft -= nright
    rcenter = [c + ' ' * nleft + dim + ' ' * nright + c]
    ntop = h - 2 - 1
    nbot = ntop // 2
    ntop -= nbot
    return '\n'.join([banner] + [row] * ntop + rcenter + [row] * nbot + [banner])

尝试:print(box_str(9, 5, '*')) 给出:

*********
*       *
*  9x5  *
*       *
*********

print(box_str(5, 3, '*'))给出:

*****
*5x3*
*****

任何更小的东西都会升高。