我需要使用 Python 中的模式显示以下'FUN'。我遇到的问题是我需要将它们全部放在一行中,每个字符之间有空格。我明白当我使用print()
函数时它将移动到下一行。我试着寻找一个例子,但没有成功。
下面是我的“F U N”代码,它将以垂直顺序打印出来。
#Pattern F
for row in range(5):
for col in range(7):
if (col==0 or col==1) or ((row==0 or row==2)):
print("F",end="")
else:
print(end=" ")
print()
print()
#Pattern U
for row in range(5): # there are 5 rows
for col in range(7): # 7 columns
if ((col==0 or col==6) and row<3) or (row==3 and (col==1 or col==5)) or (row==4 and col>1 and col<5):
print("U", end="")
else:
print(end=" ")
print()
print()
# Pattern N
for row in range(5):
for col in range(9):
if (col==0 or col==1 or col==6 or col==7) or (row==col-1): #and (col>0 and col<5)):
print("N",end="")
else:
print(end=" ")
print()
答案 0 :(得分:1)
我会选择不直接打印字符,而是先使用专用函数将它们保存到字符串中。一旦你有这些字符串,它们很容易组合成单词:
def pattern_f():
return [
''.join([
'F' if (col == 0 or col == 1 or row == 0 or row ==2) else ' '
for col in range(7)]) for row in range(5)
]
def pattern_u():
return [
''.join([
'U' if ((col==0 or col==6) and row<3) or (row==3 and (col==1 or col==5)) or (row==4 and col>1 and col<5) else ' '
for col in range(7)]) for row in range(5)
]
def pattern_n():
return [
''.join([
'N' if (col==0 or col==1 or col==6 or col==7) or (row==col-1) else ' '
for col in range(7)]) for row in range(5)
]
##separate printing:
for string in pattern_f():
print(string)
print()
for string in pattern_u():
print(string)
print()
for string in pattern_n():
print(string)
print()
##combining
for f,u,n in zip(pattern_f(), pattern_u(), pattern_n()):
print(f,u,n)
这给出了以下输出:
FFFFFFF
FF
FFFFFFF
FF
FF
U U
U U
U U
U U
UUU
NN N
NNN N
NN N N
NN N N
NN NN
FFFFFFF U U NN N
FF U U NNN N
FFFFFFF U U NN N N
FF U U NN N N
FF UUU NN NN
希望这有帮助。