Extra newlines in python
<p>I have this python code which is used to  give direction to <strong>m</strong> to reach <strong>p</strong>. </p>

<p>Here is the code:</p>

<pre><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 &gt; 0):
        print "DOWN\n"*down_up
    else:
        print "UP\n"

    right_left = p_column - m_column
    if(right_left &gt; 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)
</code></pre>

<p>Input:</p>

<pre><code>&gt; 6
&gt; ---
&gt; ---
&gt; -m-
&gt; ---
&gt; ---
&gt; p--
</code></pre>

<p>Expected output:</p>

<pre><code>DOWN
DOWN
DOWN
LEFT
</code></pre>

<p>My output:</p>

<pre><code>DOWN
DOWN
DOWN

LEFT
</code></pre>

<p>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?</p>

<p>You are hard-coding a newline after each <code>'DOWN'</code> or <code>'RIGHT'</code> every time you do this:</p>

<pre><code>    print "DOWN\n"*down_up
    print "RIGHT\n"*right_left
</code></pre>

<p>The resulting strings will be <code>'DOWN'</code> or <code>'RIGHT'</code> 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:</p>

<pre><code>    print "DOWN\n"*(down_up-1) + 'DOWN'
    print "RIGHT\n"*(right_left-1) + 'RIGHT'
</code></pre>

<p>Or use <code>str.join</code>:</p>

<pre><code>    print '\n'.join("DOWN" for i in range(down_up))
    print '\n'.join("RIGHT" for i in range(right_left))
</code></pre>

python python-2.7