0

我正在完成我必须为作业编写的代码,但问题是当我打印出代码时,它的格式不正确。我目前在列表中有歌曲的行,当我打印出来时,列表包括括号,这不是我想要的。我还希望每行都有一个新空间,我尝试使用 '\n' 换行符来设置它,但它也不起作用。附件是我的代码,对这种格式的任何帮助都会很好。谢谢!

定义主():

    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
4

2 回答 2

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

您正在添加节,这是一个列表

或者你可以做

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

并摆脱 for 节

或者可能是最好的解决方案

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)
于 2013-09-21T16:43:02.047 回答
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
于 2013-09-21T16:57:50.213 回答