初学者python:格式化行

时间:2013-09-21 16:38:20

标签: python formatting format

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

def 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

2 个答案:

答案 0 :(得分:0)

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

你正在添加stanzal这是一个列表

另外你可以做

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)

答案 1 :(得分: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