在循环中使用 end= 参数(Python)



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

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=,金字塔都打印正确,但每行后都有换行符。以下是输出:

使用结束=:

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

没有结束=:

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

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

打印任何没有换行符的输出的最直接方法是使用sys.stdout.write.这会将字符串写入stdout而不追加新行。

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

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

您将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)

试试这个算法:

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)