1

My Python code:

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

prints this:

# # #
# # #
# # #

why not this:

###
###
###

Thanks much!

1

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the documentation quote. It's nice to know the why, not just the how.
2

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

4 Comments

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.
@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: 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: 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.
2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.