gpt4 book ai didi

python - 如何阻止 Python 在迭代时添加空格?

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

我的 Python 代码:

mapArray = [["#","#","#"],["#","#","#"],["#","#","#"]]
for row in mapArray:
for cell in row:
print cell,
print
print

打印这个:

# # #
# # #
# # #

为什么不这样:

###
###
###

非常感谢!

最佳答案

当我希望 Python 只打印我告诉它的内容而不插入换行符或空格时,我的首选解决方案是使用 sys.stdout:

from sys import stdout
mapArray = [["#","#","#"],["#","#","#"],["#","#","#"]]
for row in mapArray:
for cell in row:
stdout.write(cell)
stdout.write("\n")
stdout.write("\n")

print statement documentation状态,“在每个对象被(转换和)写入之前写入一个空格,除非输出系统认为它位于一行的开头。” 这就是为什么 sys.stdout 是这里的首选解决方案,也是您在输出中看到空格的原因。

关于python - 如何阻止 Python 在迭代时添加空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2960978/

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