python错误:"str"对象没有属性"upper()" [英] python error : 'str' object has no attribute 'upper()'

查看:343
本文介绍了python错误:"str"对象没有属性"upper()"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm discovering possibilities of string formatting with .format( ) method in Python 3 but i raised an error that i do not understand.

所以,为什么以下行可以[让我认为可以完全像传递给format()的参数那样使用"0"]:

So, why the following line is ok [wich let me think that "0" can be used exactly like the argument passed to format()]:

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

但这不是[在{0}中将方法或函数应用于0无效吗?]

but not this one [applying a method or a function to 0 in {0} doesn't work?]:

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

引发以下错误:

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

为什么引发的错误说明我将upper用作属性而不是方法? 还有另一种方法可以做到:

Why the raised error says i've used upper as an attribute and not as a method? And is there another way to do it than:

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

谢谢!

推荐答案

字符串格式使用受限制的类似Python的语法.它没有将它们视为实际的Python表达式.此语法不支持调用,仅支持预订(按数字或不带引号(!)的名称编制索引),并且支持属性访问.

String formatting uses a limited Python-like syntax. It is not treating them as actual Python expressions. Calls are not supported in this syntax, only subscription (indexing by number or by unquoted (!) name), and attribute access is supported.

请参见 格式字符串语法 文档,该字段将字段命名部分限制为:

See the Format String Syntax documentation, which limits the field naming part to:

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

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

The error you see stems from the attribute_name value having been set to 'upper()', so the identifier includes the parentheses. String objects only have an attribute named upper, and in actual Python expressions the () part is a separate call expression applied to the result of the attribute lookup:

>>> 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字符串格式支持完整表达式的字符串文字,因为在编译Python代码时,解释器会直接对其进行解析.使用此类文字,您可以执行以下操作:

As of Python 3.6 you can use the new f-string formatted string literals that support full expressions, because those are parsed directly by the interpreter when compiling the Python code. Using such literals you can do:

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'

这篇关于python错误:"str"对象没有属性"upper()"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆