views:

79

answers:

3

My Python code:

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

prints this:

# # #
# # #
# # #

why not this:

###
###
###

Thanks much!

+2  A: 

Change your print cell, to sys.stdout.write(cell). After importing sys, of course.

Will McCutchen
That works, thanks!Is that the most attractive solution?
Darin
Note that print converts objects its given to strings, while the `write` method of file-like objects takes strings. You may want `sys.stdout.write(str(cell))`, depending on what `cell` is.
Matt Anderson
@Darin: It's the most attractive if you'd rather not switch to Python 3, which has "sep" and "end" as two of the keyword arguments for its print function (as print is no longer a statement but a function in Python 3). sep is assigned the space character by default and end is assigned \n, so print('a', 'b') would return "a b" followed by a newline, but print('a', 'b', sep='', end='') would return 'ab' with no trailing newline. print() (no arguments) results in a newline being sent to output, just as print used by itself does in Python 2.
JAB
@JAB: Python 2.6 already has the `print` function if you want it:`from __future__ import print_function; print("a", "b", sep="", end=""); print("c")`
Philipp
Philipp: Oh yeah, I forgot about that. I knew 2.6 was forwards-compatible in some way, but I forgot what the specifics of it were.
JAB
+2  A: 

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.

Eli Courtwright
Thanks for the documentation quote. It's nice to know the why, not just the how.
Darin
+2  A: 

Or you could simply use join to build the string and then print it.

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