我正在尝试格式化字符串,但是会生成AttributeError

时间:2019-11-12 18:29:40

标签: python

这是一段代码

def lyrics(animal, sound):

    print('''Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!
And on that farm he had a {1}, Ee-igh, Ee-igh, Oh!
With a {2}, {2} here and a {2}, {2} there.
Here a {2}, there a {2}, everywhere a {2}, {2}.
Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!''').format(animal, sound)

这是错误消息

File "c6e1.py", line 19, in main
    lyrics("buffalo", "boo")
  File "c6e1.py", line 16, in lyrics
    Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!''').format(animal, sound)
AttributeError: 'NoneType' object has no attribute 'format'

请帮助!

3 个答案:

答案 0 :(得分:1)

尝试一下:

def lyrics(animal, sound):

    print('''Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!
And on that farm he had a {0}, Ee-igh, Ee-igh, Oh!
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, Ee-igh, Ee-igh, Oh!'''.format(animal, sound))

print("""any_string""")将返回NoneType,并且您无法对其进行字符串格式化。您需要执行print("""any_string""".fomrat(formatters))

注意:像在上面的函数中那样,在.format()中使用位置参数会产生另一个错误,因为它的索引从0开始。

答案 1 :(得分:0)

首先,您在print()的返回值(无)上调用format函数。您必须在括号内的字符串上调用它。 其次,format()的参数索引从零开始,因此您需要对其进行适当调整。

答案 2 :(得分:0)

从python 3.6开始,您还可以使用f-strings

def lyrics(animal, sound):

    print(f'''Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!
And on that farm he had a {animal}, Ee-igh, Ee-igh, Oh!
With a {sound}, {sound} here and a {sound}, {sound} there.
Here a {sound}, there a {sound}, everywhere a {sound}, {sound}.
Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!''')