如何在 python 中打印形状?寻找一种不同且更有效的方法

how to print shapes in python? looking into a different and more efficient way

试过很多方法,比如逐行打印:

打印(" ------ ")

print("||") 打印(“| |”)

打印(" ------ ")

还有 * ,

打印(“********”)

print("*") 打印 (" *")

打印(“********”)

就我个人而言,我认为破折号 (-) 看起来比星号 (*) 更平滑。还有其他方法吗?

你更想拥有以下哪一个:

┌────────┐
│        │
│        │
└────────┘

 --------
|        |
|        |
 --------

除非您出于某种原因需要输出纯 ASCII — 或者您想要那种复古的 APPLE ][外观 — 您应该使用 box-drawing characters 绘制方框。而且它真的不比用连字符和竖线以及其他不适用于画线的东西更难:

horiz = '\u2500'
vert = '\u2502'
ul = '\u250c'
ur = '\u2510'
ll = '\u2514'
lr = '\u2518'

def box(width, height):
  top = ul + horiz*(width-2) + ur
  middle = vert + ' '*(width-2) + vert
  bottom = ll + horiz*(width-2) + lr
  lines = [top] + [middle]*(height-2) + [bottom]
  return '\n'.join(lines)

print(box(10, 4))

有时甚至更容易从 PyPI 中获取一个库来做你想做的事情,比如 terminaltables for drawing tables with borders, or asciitree 用于像 DOS 和 Unix 树命令一样绘制树等


或者,根据您的尝试,您可能真的想编写一个 curses or urwid 或类似的全屏控制台应用程序,并让它在您的 windows 周围绘制方框。

胡言乱语:

def box(w,h):
   s='┌%s┐'%('─'*w)
   for i in range(int(h/2)):
      s+='\n│%s│'%(' '*w)
   s+='\n└%s┘'%('─'*w)
   return s

print(box(5,5))