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

标签 python arrays multidimensional-array iteration

我的 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/

相关文章:

c++ - 通过指针调整数组大小

php - 数组 : 4th dimension, isset 返回不可靠

javascript - JS多维数组排序列表

python - Openerp 7 复选框

c - 如何访问仅给定指针的数组元素

python - 如何以编程方式获取 Python 中已安装模块的版本?

java - 在特定 INPUT 值后获取 ArrayIndexOutOfBoundsException

c++ - 将多维数组传递给参数类型为 double * 的函数

Python:缩进错误

python - 使用pyenv在Python的两个系统版本之间切换