【问题标题】:How to stop Python from adding whitespace while iterating?如何阻止 Python 在迭代时添加空格?
【发布时间】:2010-06-02 19:32:34
【问题描述】:

我的 Python 代码:

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

打印这个:

# # #
# # #
# # #

为什么不这样:

###
###
###

非常感谢!

【问题讨论】:

标签: python arrays multidimensional-array iteration


【解决方案1】:

当我希望 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 表示 "A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line." 这就是为什么 sys.stdout 是这里的首选解决方案,也是您在输出中看到空格的原因。

【讨论】:

  • 感谢文档报价。很高兴知道原因,而不仅仅是方法。
【解决方案2】:

将您的 print cell, 更改为 sys.stdout.write(cell)。当然是在导入sys 之后。

【讨论】:

  • 请注意 print 将其给定的对象转换为字符串,而类文件对象的 write 方法接受字符串。您可能需要sys.stdout.write(str(cell)),具体取决于cell 是什么。
  • @Darin:如果你不想切换到 Python 3,这是最有吸引力的,它有“sep”和“end”作为其 print 函数的两个关键字参数(因为 print 不是更长的语句,但 Python 3 中的函数)。 sep 默认为空格字符,end 为 \n,因此 print('a', 'b') 将返回 "a b" 后跟换行符,但 print('a', 'b', sep=' ', end='') 将返回没有尾随换行符的 'ab'。 print() (无参数)导致将换行符发送到输出,就像 Python 2 中自己使用的 print 一样。
  • @JAB:如果你想要的话,Python 2.6 已经有了print 函数:from __future__ import print_function; print("a", "b", sep="", end=""); print("c")
  • 菲利普:哦,是的,我忘了。我知道 2.6 在某种程度上是向前兼容的,但我忘记了它的细节。
【解决方案3】:

或者您可以简单地使用join 来构建字符串然后打印它。

>>> mapArray = [["#","#","#"],["#","#","#"],["#","#","#"]]
>>> print '\n'.join([''.join(line) for line in mapArray])
###
###
###

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2020-08-09
    相关资源
    最近更新 更多