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

2024-04-19 22:25:27 发布

您现在位置: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语句或循环,只能使用字符串操作。我不知道如何这样做。任何帮助或提示都将不胜感激,谢谢


Tags: of字符串boxinput宽度高度尺寸space
1条回答
网友
1楼 · 发布于 2024-04-19 22:25:27

修改为不包含任何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*
*****

任何更小的东西都会升高

相关问题 更多 >