[英]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:我想用“#”打印一个方形图案,output 应该是这样的:
# # # # #
# #
# #
# #
# # # # #
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:来的output是这样的:
# # # # #
#
#
#
#
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我注意到标签之间的空格,使用这个 function 它也应该给你自定义尺寸
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.