Python:'{0.lower()}'。format('A')产生'str'对象没有属性'lower()'

duh*_*ime 3 python attributeerror

在Python中,字符串有一个方法lower()

>>> dir('A')
[... 'ljust', 'lower', 'lstrip', ...]
Run Code Online (Sandbox Code Playgroud)

但是,当尝试时'{0.lower()}'.format('A'),响应指出:

>>> '{0.lower()}'.format('A')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'lower()'
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我理解为什么在这种情况下,上面的行会引发AttributeError吗?似乎它不应该是AttributeError,尽管我一定会误会。任何帮助了解这一点将非常欢迎!

编辑:我知道我不能在format调用内调用lower()方法(尽管如果可能的话,它会很整洁);我的问题是为什么这样做会引发AttributeError。在这种情况下,此错误似乎会引起误解。

sna*_*erb 8

您不能从格式规范内调用方法。格式说明符中的点符号是一种查找属性名称并呈现其值的方法,而不是调用函数的方法。

0.lower()尝试在字面上名为“ lower()” 的字符串上查找属性。您需要在格式化之前调用该方法。

>>> '{0.lower()}'.format('A')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'lower()'
>>> '{0}'.format('A'.lower())
'a'
Run Code Online (Sandbox Code Playgroud)