简体   繁体   中英

Printing a square pattern in Python with one print statement

I want to print a square pattern with "#", the output should look something like this:

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

The code I was able to write is this:

n=10
for i in range (1,6):  
    for j in range(1,6):
        if i ==1 or 1==n or j==1 or j==n:
            print("#", end= ' ')

        else:
            print(" ", end="")
    print()

The output that came is this:

# # # # # 
#     
#     
#     
#  

I also would like to know if it's possible to only have one print statement instead of many. Thank you.

This works!

s=5
print(" ".join("#"*s))
for i in range(0,s-2):
  print("#"+" "*(s+2)+"#")
print(" ".join("#"*s))

>>>
# # # # #
#       #
#       #
#       #
# # # # #

Single line:

print(" ".join("#"*s)+"\n"+("#"+" "*(s+2)+"#"+"\n")*(s-2)+" ".join("#"*s))

>>>
# # # # #
#       #
#       #
#       #
# # # # #

A simple one-liner for this with a whole square filled in could be

size = 6
print('\n'.join([' '.join('#' * size)] * size))

Or if you want the same pattern in the original

print(' '.join('#' * size))
print('\n'.join('#' * (size - 1)))

I noticed the empty spaces in between the hashtags, use this function it should give you custom dimensions too


def createSquare(xLen,yLen):
    for i in range(1,yLen):
        if i == 1 or i == yLen-1:
            print("# "*xLen)
        else:
            print("#"+" "*int(xLen*2-3)+"#")
                


createSquare(10,10)

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