intelis
intelis

Reputation: 8068

Python "\n" tag extra line

I am trying to build a simple board in command line.

Problem: When i use "\n" for ending current line, it adds an extra blank line. How can i fix that?

Code:

def drawBoard():
    board = [ [0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0],
              [0,0,0,0,3,2,1,0,0],
              [0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0]
            ]
    return board

def printBoard():
    for i in drawBoard():
        for a in i:
            print a,
        print "\n"

printBoard()

Output:

0 0 0 0 0 0 0 0 0 

0 0 0 0 0 0 0 0 0 

0 0 0 0 0 0 0 0 0 

0 0 0 0 3 2 1 0 0 

0 0 0 0 0 0 0 0 0 

0 0 0 0 0 0 0 0 0 

0 0 0 0 0 0 0 0 0 

0 0 0 0 0 0 0 0 0 

0 0 0 0 0 0 0 0 0 

Thanks for your help.

Upvotes: 3

Views: 111924

Answers (4)

Paul Biester
Paul Biester

Reputation: 25

The print function in python adds itself \n

You could use

import sys
sys.stdout.write(a)

instead

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

use join(), don't rely on the , for formatting, and also print automatically puts the cursor on a newline every time, so no need of adding another '\n' in your print.

In [24]: for x in board:
    print " ".join(map(str,x))
   ....:     
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 3 2 1 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0

Upvotes: 8

px1mp
px1mp

Reputation: 5372

Add , after the print "\n" line

so that it reads print "\n",

Upvotes: 0

DSM
DSM

Reputation: 353379

This:

    print "\n"

is printing out two \n characters -- the one you tell it to, and the one that Python prints out at the end of any line which doesn't end with a , like you use in print a,. Simply use

    print

instead.

Upvotes: 8

Related Questions