【问题标题】:Using end= parameter in loop (Python)在循环中使用 end= 参数(Python)
【发布时间】:2018-10-23 21:43:18
【问题描述】:

我想要的输出是两个由两个空格分隔的半金字塔。

length = int(input("Enter size of pyramid."))
hashes = 2
for i in range(0, length):
    spaces = length - (i+1)
    hashes = 2+i
    print("", end=" "*spaces)
    print("#", end=" "*hashes)
    print("  ", end="")
    print("#" * hashes)

但是,这最终只打印左金字塔上每一行的第一个哈希值。如果我去掉第 7 行中的end=,金字塔都打印正确,但每行后都有换行符。以下是输出:

结束=:

   #    ##
  #     ###
 #      ####
#       #####

没有结束=:

   ##
  ##
  ###
  ###
 ####
  ####
#####
  #####

我现在想要的只是第二个输出,但没有换行符。

【问题讨论】:

  • 没有新行是什么意思?
  • @DanielMesejo 每行之间没有换行符。

标签: python python-3.x


【解决方案1】:

在没有换行符的情况下打印您想要的任何输出的最直接方法是使用sys.stdout.write。这会将字符串写入stdout,而不添加新行。

>>> import sys
>>> sys.stdout.write("foo")
foo>>> sys.stdout.flush()
>>> 

正如您在上面看到的,"foo" 没有换行符。

【讨论】:

    【解决方案2】:

    您将end 参数乘以哈希数,而不是乘以正文部分。

    试试这个修改:

    length = int(input("Enter size of pyramid."))
    hashes = 2
    for i in range(0, length):
        spaces = length - (i+1)
        hashes = 2+i
        print(" " * spaces, end="")
        print("#" * hashes, end="")
        print("  ", end="")
        print("#" * hashes)
    

    【讨论】:

      【解决方案3】:

      试试这个算法:

      length = int(input("Enter size of pyramid."))
      # Build left side, then rotate and print all in one line
      for i in range(0, length):
          spaces = [" "] * (length - i - 1)
          hashes = ["#"] * (1 + i)
          builder = spaces + hashes + [" "]
          line = ''.join(builder) + ''.join(builder[::-1])
          print(line)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-20
        • 1970-01-01
        • 1970-01-01
        • 2017-07-24
        • 2012-12-12
        • 2014-10-03
        • 2017-03-25
        • 2021-11-27
        相关资源
        最近更新 更多