2013-09-21 27 views
0

我正在完成這個代碼,我不得不爲一項任務編寫代碼,但問題是當我打印出代碼時,它的格式不正確。我現在有一個列表中的歌曲的線,當我打印出來,列表包括括號,這是不是我想要的。我也希望每一行有一個新的空間,我嘗試使用'\ n'換行符來設置它,但它也不會工作。附加是我的代碼,這種格式的任何幫助將是很好的。謝謝!初學者python:格式化行

高清的main():

oldMac = [] 
    for stanza in range(3): 
    animal = raw_input("What animal? ") 
    animalSound = raw_input("What sound does a %s make? " %(animal)) 
    stanza1 = [ 
      "Old MacDonald had a farm, E-I-E-I-O,", 
      "And on his farm he had a %s, E-I-E-I-O" %(animal), 
      "With a %s-%s here - " %(animalSound, animalSound), 
      "And a %s-%s there - " %(animalSound, animalSound), 
      "Here a %s there a %s" %(animalSound, animalSound), 
      "Everywhere a %s-%s" %(animalSound, animalSound), 
      "Old MacDonald had a farm, E-I-E-I-O"] 

    print stanza1 

    for stanza in range(1): 
     oldMac = oldMac + stanza1 

print "Here are the completed song lyrics: " 
print 
print oldMac 

回答

0
for stanza in stanza1: 
     oldMac = oldMac + stanza + "\n" 

你添加stanzal這是一個列表

alternativly你可以做

oldMac += "\n".join(stanza1) 

和節

擺脫

或probabbly的最佳解決方案

stanza = """Old MacDonald had a farm, E-I-E-I-O, 
      And on his farm he had a {0}, E-I-E-I-O 
      With a {1}-{1} here - 
      And a {1}-{1} there - 
      Here a {1} there a {1} 
      Everywhere a {1}-{1} 
      Old MacDonald had a farm, E-I-E-I-O""".format(animal, animalSound) 
0

改變線

print stanza1 

print '\n'.join(stanza1) 

輸出

What animal? cow 
What sound does a cow make? moo 

Old MacDonald had a farm, E-I-E-I-O, 
And on his farm he had a cow, E-I-E-I-O 
With a moo-moo here - 
And a moo-moo there - 
Here a moo there a moo 
Everywhere a moo-moo 
Old MacDonald had a farm, E-I-E-I-O