【问题标题】:How to make framed box using user input and string manipulation in python?如何在 python 中使用用户输入和字符串操作制作框架框?
【发布时间】:2021-01-18 17:15:34
【问题描述】:

这是我所拥有的:

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 语句或循环,只能使用字符串操作。我不确定如何以这种方式这样做。任何帮助或提示将不胜感激,谢谢!

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 我写了一些代码,它得到了上图的答案,但我需要能够使它工作,以便另一组宽度和高度给出不同的答案。我的代码,当我输入 11 的宽度和 8 的高度时,仍然给我一个 7x5 的框。我不知道还能做什么
  • 如果您要求3x5 下的任何框,预期的行为是什么?

标签: python python-3.x string input dimensions


【解决方案1】:

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

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

【讨论】:

  • 很遗憾我不能使用 if 语句或循环
  • 好吧,如果你愿意让盒子看起来很奇怪,如果尺寸太小而无法显示尺寸,那么删除这些测试。已经没有循环,所以在这方面没有什么可以改变的。
  • 非常感谢您,我将审查并添加一些用户输入以使代码符合分配规则。
猜你喜欢
  • 1970-01-01
  • 2022-11-07
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
  • 2015-04-29
  • 2019-05-14
  • 1970-01-01
  • 2022-11-03
相关资源
最近更新 更多