2015-11-24 341 views
0
def linebreak(fruits): 
    ''' 
    >>> fruits = 'apple banana pear' 
    >>> linebreak(fruits) 
    apple 
    banana 
    pear 
    ''' 
    response = '' 
    for fruit in fruits.split(): 
     response += fruit + '\n' 

    return response 

if __name__ == '__main__': 
    import doctest 
    doctest.testmod() 

Expected: 
    apple 
    banana 
    pear 

Got: 
    'apple\nbanana\npear\n' 

我基本上想要一個返回print的函數。我希望代碼不要太混亂。我掃描了互聯網,但我能找到的所有人都是在打印時詢問有關換行的問題,而不是在返回時提問。Python:如何在函數中返回一個換行符

+1

輸出**有**得到換行符 - 嘗試進行測試'print linebreak(fruits)'。 – jonrsharpe

+0

您對交互模式的自動打印行爲感到困惑。 'return'和'print'做了完全不同的事情。如果您想打印某些內容,請使用「打印」。 – user2357112

回答

2

>>> linebreak(fruits)顯示返回值的repr(),它是一個Python字符串。

你想要的是>>> print linebreak(fruits)實際上打印內容返回值,而不是它的再版的

>>> 'foo\nbar' 
'foo\nbar' 
>>> print 'foo\nbar' 
foo 
bar 

僅供參考,您的整個功能可以在一個線路被簡化:

return '\n'.join(fruits.split()) 
相關問題