字符串格式化函数中的AttributeError

问题描述 投票:0回答:3

我在使用以下代码片段时遇到了 AttributeError 。对于这个问题,我将不胜感激。

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'

欢迎任何见解和建议。谢谢!

python
3个回答
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
开始。


0
投票

首先,对 print() 的返回值(即 None)调用 format 函数。您必须在括号内的字符串上调用它。 其次,format() 的参数索引是从零开始的,所以你需要好好调整它们。


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!''')
© www.soinside.com 2019 - 2024. All rights reserved.