How to stop Python from adding whitespace while iterating?
My Python code:
mapArray = [["#","#","#"],["#","#","#"],["#","#","#"]]
for row in mapArray:
for cell in row:
开发者_开发知识库 print cell,
print
print
prints this:
# # #
# # #
# # #
why not this:
###
###
###
Thanks much!
My preferred solution when I want Python to only print what I tell it to without inserting newlines or spaces is to use sys.stdout
:
from sys import stdout
mapArray = [["#","#","#"],["#","#","#"],["#","#","#"]]
for row in mapArray:
for cell in row:
stdout.write(cell)
stdout.write("\n")
stdout.write("\n")
The print statement documentation states, "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."
This is why sys.stdout
is the preferred solution here and is the reason why you're seeing spaces in your output.
Change your print cell,
to sys.stdout.write(cell)
. After importing sys
, of course.
Or you could simply use join
to build the string and then print it.
>>> mapArray = [["#","#","#"],["#","#","#"],["#","#","#"]]
>>> print '\n'.join([''.join(line) for line in mapArray])
###
###
###
精彩评论