代码之家  ›  专栏  ›  技术社区  ›  Adam Grey

在循环中使用end=parameter(Python)

  •  0
  • Adam Grey  · 技术社区  · 6 年前

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

    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)
    

    end=

    结束=:

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

    无结束=:

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

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

    3 回复  |  直到 6 年前
        1
  •  2
  •   Josh Weinstein    6 年前

    打印任何想要的输出而不使用换行符的最直接的方法是使用 sys.stdout.write stdout 不添加新行。

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

    如上图所示, "foo" 没有换行。

        2
  •  1
  •   John Gordon    6 年前

    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
  •  1
  •   Milan    6 年前

    尝试此算法:

    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)