首页 > 解决方案 > 打印 Python 上的额外新行

问题描述

我有一个有趣的小功能,可以用星号打印菱形。它看起来像这样:

from time import sleep

while True:
    whitespaces_count = 0
    dots_count = 8
    for _ in range(0, 5):
        print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
        whitespaces_count += 2
        dots_count -= 2
        sleep(0.15)
    whitespaces_count = 6
    dots_count = 2
    for _ in range(0, 4):
        print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
        whitespaces_count -= 2
        dots_count += 2
        sleep(0.15)
    print("\n")

它工作正常,但是,在每个print命令之后,它都会打印额外的空白行,因此输出如下所示:

********
***  ***
**    **
*      *

*      *
**    **
***  ***
********

但我希望它看起来像这样:

********
***  ***
**    **
*      *
*      *
**    **
***  ***
********


我在做什么错?

标签: pythonoptimization

解决方案


你的问题不是print,而是你的第一个循环运行了一个额外的时间,打印没有点,所有的空白。将其更改为循环range(4)而不是range(5)多余的行消失。


旁注:您应该真正利用循环本身来确定要使用多少个星号和空格print;您正在使用 arange来决定要运行多少个循环,但它可以执行双重任务,从而允许这样做(最低限度的固定代码):

whitespaces_count = 0
dots_count = 8
for _ in range(4):
    print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
    whitespaces_count += 2
    dots_count -= 2
    sleep(0.15)

成为:

for whitespaces_count in range(0, 8, 2):
    dots_count = 8 - whitespaces_count
    print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
    sleep(0.15)

或者让循环做更多的工作,将更多的工作推给性能优于手写代码的内置程序(并dots_count参考每边的点数):

for whitespaces_count, dots_count in zip(range(0, 8, 2), range(4, 0, -1)):
    print("*"*dots_count + " "*whitespaces_count + "*"*dots_count)
    sleep(0.15)

推荐阅读