Ibram Marzouk Ibram Marzouk - 2 months ago 6
Python Question

Extra newlines in python

I have this python code which is used to give direction to m to reach p.

Here is the code:

#!/bin/python
def displayPathtoPrincess(n,grid):
m = "m"
p = "p"

for i in range(n):
if(m in grid[i]):
m_column = grid[i].find(m)
m_row = int(i + 1)
#print "{0}x{1} \n".format(int(i + 1), m_position + 1)

if(p in grid[i]):
p_column = grid[i].find(p)
p_row = int(i + 1)
#print "{0}x{1} \n".format(int(i + 1), p_position + 1)

down_up = p_row - m_row
if(down_up > 0):
print "DOWN\n"*down_up
else:
print "UP\n"

right_left = p_column - m_column
if(right_left > 0):
print "RIGHT\n"*right_left
else:
print "LEFT\n"


m = input()

grid = []
for i in xrange(0, m):
grid.append(raw_input().strip())

displayPathtoPrincess(m,grid)


Input:

> 6
> ---
> ---
> -m-
> ---
> ---
> p--


Expected output:

DOWN
DOWN
DOWN
LEFT


My output:

DOWN
DOWN
DOWN

LEFT


As you can see in my output, the program adds a new line whenever it changes the direction. Any ideas on how to stop this new line from appearing?

Answer

You are hard-coding a newline after each 'DOWN' or 'RIGHT' every time you do this:

    print "DOWN\n"*down_up
    print "RIGHT\n"*right_left

The resulting strings will be 'DOWN' or 'RIGHT' followed by a newline, the specified number of times. That means that such strings will end with an unwanted newline. The smallest fix is to multiply by one fewer than the necessary number, and then add the last bit:

    print "DOWN\n"*(down_up-1) + 'DOWN'
    print "RIGHT\n"*(right_left-1) + 'RIGHT'

Or use str.join:

    print '\n'.join("DOWN" for i in range(down_up))
    print '\n'.join("RIGHT" for i in range(right_left))
Comments