python错误:“str”对象没有属性“upper()”

python错误:“str”对象没有属性“upper()”,python,python-3.x,formatting,attributeerror,Python,Python 3.x,Formatting,Attributeerror,我正在Python3中发现使用.format方法进行字符串格式化的可能性,但我提出了一个我不理解的错误 那么,为什么下面这行是ok[让我认为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

我正在Python3中发现使用.format方法进行字符串格式化的可能性,但我提出了一个我不理解的错误

那么,为什么下面这行是ok[让我认为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表达式。此语法中不支持调用,仅支持按数字或无引号的订阅索引!支持名称和属性访问

请参阅文档,该文档将字段命名部分限制为:

field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
您看到的错误源于属性_name值被设置为“上限”,因此标识符包含括号。字符串对象只有一个名为upper的属性,在实际的Python表达式中,该部分是应用于属性查找结果的单独调用表达式:

>>> 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的语法。它没有将它们视为实际的Python表达式。此语法中不支持调用,仅支持按数字或无引号的订阅索引!支持名称和属性访问

请参阅文档,该文档将字段命名部分限制为:

field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
您看到的错误源于属性_name值被设置为“上限”,因此标识符包含括号。字符串对象只有一个名为upper的属性,在实际的Python表达式中,该部分是应用于属性查找结果的单独调用表达式:

>>> 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表达式。您可以创建索引,也可以创建属性,但不能调用。请参阅。@MartijnPieters引发错误,但是AttributeError:'str'对象没有属性'upper'似乎有误导性?毕竟,str确实有一个.upperattribute@Chris_Rands:否,因为除非这些字符是属性名称的一部分,否则您永远不会在属性中看到错误。str对象上确实存在的实际属性名为upper。尝试getattrstr'upper'和getattrstr'upper'。调用表达式通常应用于属性查找的结果。因为格式化语法不使用Python表达式。您可以创建索引,也可以创建属性,但不能调用。请参阅。@MartijnPieters引发错误,但是AttributeError:'str'对象没有属性'upper'似乎有误导性?毕竟,str确实有一个.upperattribute@Chris_Rands:否,因为除非这些字符是属性名称的一部分,否则您永远不会在属性中看到错误。str对象上确实存在的实际属性名为upper。尝试getattrstr'upper'和getattrstr'upper'。调用表达式通常应用于属性查找的结果。