【问题标题】:Python: '{0.lower()}'.format('A') yields 'str' object has no attribute 'lower()'Python:'{0.lower()}'.format('A') 产生 'str' 对象没有属性 'lower()'
【发布时间】: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


【解决方案1】:

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

0.lower() 尝试在字符串 literally 上查找名为“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'

【讨论】:

  • 啊,这条评论解释了它!我会尽快接受这个答案...
【解决方案2】:

正如其他人所说,您不能在格式表达式中执行此操作。不过它可以在 f-string 中工作:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-09-22
  • 2019-03-19
  • 2021-08-23
  • 2014-12-09
  • 2020-10-06
  • 2016-04-15
  • 2016-01-30
  • 2020-12-08
相关资源
最近更新 更多