2016-09-24 83 views
0

我有這個python代碼,用於指示m達到ppython中的額外換行符

下面是代碼:

#!/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) 

輸入:

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

預期輸出:

DOWN 
DOWN 
DOWN 
LEFT 

我的輸出:

DOWN 
DOWN 
DOWN 

LEFT 

正如您在輸出中看到的,程序在改變方向時會添加一條新線。關於如何阻止這一新行出現的任何想法?

+0

你不需要'\ N'後'打印'除非你以昏迷結束 –

+0

@ Jean-FrançoisFabre,當我刪除所有'\ n'時,我得到以下輸出: DOWNDOWNDOWN LEFT –

回答

0

你硬編碼換行符每個'DOWN''RIGHT'你這樣做,每次經過:

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

結果字符串會跟着一個換行符的指定次數'DOWN''RIGHT'。這意味着這樣的字符串將以不需要的換行符結束。最小的解決辦法是由一個比必要數量少繁殖,然後添加最後一位:

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

或者使用str.join

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

非常感謝! –