问题描述
这是我所拥有的:
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*
*****
任何较小的东西都会升高。