如何使用功能打印此框?

时间:2017-12-02 03:29:14

标签: python printing

https://i.imgur.com/sywMx9V.png真的很困惑这是如何工作的,如果我在这篇文章中将错误格式化了我的错误。

4 个答案:

答案 0 :(得分:2)

如果您只是想在控制台中打印,请尝试以下操作:

def printBox():
  print("+-----+")
  print("|     |")
  print("|     |")
  print("+-----+")

printBox()

答案 1 :(得分:1)

print("""
+----------+
|          |
|          |
+----------+
""")

这么简单。

答案 2 :(得分:1)

对于任意情况,最好定义框的宽度:

def box(w):
    final_box = ['+{}+'.format('-'*w) if i == 0 or i == w-2 else "|{}|".format(' '*(w)) for i in range(w-1)]
    for i in final_box:
        print i
box(5)

输出:

 +-----+
 |     |
 |     |
 +-----+

答案 3 :(得分:1)

也许让变量变得更好:

>>> box = "+----+\n|     |\n|     |\n+----+"
>>> print(box)
+----+
|    |
|    |
+----+

或功能:

>>> def box(w, h):
...     head = '+' + '-'*w*2 + '+'
...     body = '|' + ' '*w*2 + '|'
...     box = head + '\n' + (body + '\n') * h + head
....    return box
>>> print(box(2, 2))
+----+
|    |
|    |
+----+
相关问题