2017-08-15 130 views
0

給出一個簡單的地圖:打印時反斜槓-n不會被解釋爲換行符?

combinations = {'a':11, 'b': 12, 'c': 13} 

讓我們打印在單獨的行的條目:

print('Combinations: ', '\n'.join(str(c) for c in combinations.iteritems())) 

..或許不是..

('Combinations: ', "('a', 11)\n('c', 13)\n('b', 12)") 

爲什麼解釋\n不作爲換行符在這裏?

回答

4

您正在使用Python 2而不是Python 3,所以print實際上是在打印一個元組。將元組轉換爲字符串將repr應用於其元素。

要麼

  • 開關到Python 3,

  • 使用__future__獲取打印功能在Python 2,

    from __future__ import print_function 
    
  • 或移除該元組。

    print 'Combinations: ', '\n'.join(str(c) for c in combinations.iteritems()) 
    
0

我不知道理解的問題,但它是不是打印()或 '\ n' 的問題,請參見後續例如:

print('first\nsecond\nthird') 
first 
second 
third 

如果您想要打印一個按鍵,每行的價值,你可以按照以下步驟操作:

print('\n'.join(str(c[0]) + ": " + str(c[1]) for c in combinations.iteritems())) 
a: 11 
c: 13 
b: 12