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

Python: '{0.lower()}'.format('A') yields 'str' object has no attribute 'lower()'

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

>>> dir('A')
[... 'ljust', 'lower', 'lstrip', ...]

但是,当尝试 '{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()'

有人能帮我理解为什么上面的行在这种情况下抛出 AttributeError 吗?这似乎不应该是一个 AttributeError,尽管我一定是弄错了。非常欢迎任何帮助理解这一点!

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

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

0.lower() 尝试查找字符串 字面上 上名为“lower()”的属性 - 相当于 getattr(some_string, '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'

正如其他人所说,您不能在格式表达式中执行此操作。它可以在 f 字符串中使用:

a = "A"
print(f"{a.lower()}")