NOx*_*NOx 1 python formatting attributeerror python-3.x
我发现在Python 3中使用.format()方法进行字符串格式化的可能性,但是我提出了一个我不理解的错误。
因此,为什么以下行可以[让我认为可以完全像传递给format()的参数那样使用“ 0”]:
s = 'First letter of {0} is {0[0]}'.format("hello")
#gives as expected: 'First letter of hello is h'
Run Code Online (Sandbox Code Playgroud)
但这不是[在{0}中将方法或函数应用于0无效吗?]:
s = '{0} becomes {0.upper()} with .upper() method'.format("hello")
Run Code Online (Sandbox Code Playgroud)
引发以下错误:
AttributeError: 'str' object has no attribute 'upper()'
Run Code Online (Sandbox Code Playgroud)
为什么引发的错误说明我已将upper用作属性而不是方法?还有另一种方法可以做到:
s = '{} becomes {} with .upper() method'.format("hello","hello".upper())
#gives as expected: 'hello becomes HELLO with .upper() method'
Run Code Online (Sandbox Code Playgroud)
谢谢!
字符串格式使用有限的类似Python的语法。它没有将它们视为实际的Python表达式。此语法不支持调用,仅支持预订(按数字或不带引号(!)的名称编制索引),并且支持属性访问。
请参阅格式字符串语法文档,该文档将字段命名部分限制为:
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
Run Code Online (Sandbox Code Playgroud)
您看到的错误源于已将attribute_name值设置为'upper()',因此标识符包括括号。字符串对象仅具有一个名为的属性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'
Run Code Online (Sandbox Code Playgroud)
从Python 3.6开始,您可以使用支持完整表达式的新的f字符串格式的字符串文字,因为在编译Python代码时,这些文字由解释程序直接解析。使用此类文字,您可以执行以下操作:
value = 'hello'
s = f'{value} becomes {value.upper()} with .upper() method'
Run Code Online (Sandbox Code Playgroud)
演示:
>>> f'{value} becomes {value.upper()} with .upper() method'
'hello becomes HELLO with .upper() method'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3959 次 |
| 最近记录: |