Skip to main content
 首页 » 编程设计

python 错误: 'str' object has no attribute 'upper()'

2025年05月04日27mate10pro

我发现了在 Python 3 中使用 .format( ) 方法格式化字符串的可能性,但我提出了一个我不理解的错误。

那么,为什么下面一行是正确的[让我认为“0”可以像传递给 format() 的参数一样使用]:

s = 'First letter of {0} is {0[0]}'.format("hello")   
#gives as expected: 'First letter of hello is h' 

但不是这个 [将方法或函数应用于 {0} 中的 0 不起作用?]:

s = '{0} becomes {0.upper()} with .upper() method'.format("hello") 

引发以下错误:

AttributeError: 'str' object has no attribute 'upper()' 

为什么出现的错误说我将 upper 用作属性而不是方法? 有没有其他方法可以做到这一点:

s = '{} becomes {} with .upper() method'.format("hello","hello".upper()) 
#gives as expected: 'hello becomes HELLO with .upper() method' 

谢谢!

请您参考如下方法:

字符串格式使用有限的类似 Python 的语法。它没有将它们视为实际的 Python 表达式。此语法不支持调用,仅支持订阅(按数字或未加引号 (!) 的名称索引)和属性访问。

参见 Format String Syntax文档,将字段命名部分限制为:

field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")* 

您看到的错误源于 attribute_name 值已设置为 'upper()',因此标识符包含括号。字符串对象只有一个名为 upper 的属性,在实际的 Python 表达式中,() 部分是一个单独的 call 表达式,应用于属性查找:

>>> value = "hello" 
>>> getattr(value, 'upper()')   # what the template engine tries to do 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'str' object has no attribute 'upper()' 
>>> getattr(value, 'upper')    # what an actual Python expression does 
<built-in method upper of str object at 0x10e08d298> 
>>> getattr(value, 'upper')()  # you can call the object that is returned 
'HELLO' 

从 Python 3.6 开始,您可以使用新的 f-string formatted string literals支持完整表达式,因为它们在编译 Python 代码时由解释器直接解析。使用这样的字面量你可以:

value = 'hello' 
s = f'{value} becomes {value.upper()} with .upper() method' 

演示:

>>> f'{value} becomes {value.upper()} with .upper() method' 
'hello becomes HELLO with .upper() method'