gpt4 book ai didi

Python "\n"标记额外行

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:21 25 4
gpt4 key购买 nike

我正在尝试在命令行中构建一个简单的板。

问题:当我使用“\n”结束当前行时,它会添加一个额外的空行。我该如何解决?

代码:

def drawBoard():
board = [ [0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,3,2,1,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]
]
return board

def printBoard():
for i in drawBoard():
for a in i:
print a,
print "\n"

printBoard()

输出:

0 0 0 0 0 0 0 0 0 

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 3 2 1 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

感谢您的帮助。

最佳答案

使用join(),不要依赖于, 进行格式化,而且print 会自动将光标放在换行符上时间,因此无需在您的 print 中添加另一个 '\n'

In [24]: for x in board:
print " ".join(map(str,x))
....:
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 3 2 1 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0

关于Python "\n"标记额外行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13434423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com