简体   繁体   中英

How do I minimize the space between characters in my nested loop?

so I'm trying to get my nested loop to display an image like in this picture:

图片

So far, this is the code that I have.

for a in range (1):
    print("#""#")
    for b in range (0,5,1):
        print("#", end=" ")
        for c in range(b):
            print(" ", end=" ")
        print("#")

I'm new to the site, so please excuse my terrible formatting. The output I'm getting seems to have an extra space per line compared to the image given, and I'm not sure how to get rid of the space. I'd appreciate any help!

I'm thinking it's the 'end=' '' statement, but if I try replacing that with just a space, my entire line goes wonky.

Thanks!

end=" " prints an space instead of a newline in the end..

I think its better to concatenate the string in this case instead of manipulating the print's end..

for i in range(5):
    print('#' + ' '*i + '#')

output:

##
# #
#  #
#   #
#    #

Like this? Changed the third print

for a in range (1):
    print("#""#")
    for b in range (0,5,1):
        print("#", end=" ")
        for c in range(b):
            print(end=" ")
        print("#")

You need to remove the whitespace in the 2nd end variable

for a in range (1):
print("#""#")
for b in range (0,5,1):
    print("#", end=" ")
    for c in range(b):
        print(" ", end="") #this end variable is what is causing your additional space
    print("#")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM