Python I';我试图格式化字符串,但它生成了AttributeError

Python I';我试图格式化字符串,但它生成了AttributeError,python,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

下面是一段代码

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'
请帮忙

试试这个:

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
,您无法对其进行字符串格式化。您需要执行
打印(“'any_string”“”).fomrat(格式化程序))


注意:在上面的函数中使用类似于
.format()
的位置参数会产生另一个错误,因为它的索引从
0

开始。首先,在print()的返回值上调用format函数,该函数为None。必须在括号内的字符串上调用它。
其次,format()参数的索引是基于零的,因此您需要对它们进行良好的调整。

来自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!''')

format()
调用需要直接在字符串后面,在
print()括号内找到它,谢谢