【发布时间】:2019-08-21 21:02:01
【问题描述】:
在 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。在这种情况下,此错误似乎具有误导性。
【问题讨论】:
-
您可能想要一个 f 字符串:
f'{'A'.lower()}.
标签: python string-formatting attributeerror