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

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

问题描述

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

那么,为什么下面这行没问题[让我认为0"可以像传递给 format() 的参数一样使用]:

s = '{0} 的第一个字母是 {0[0]}'.format("hello")#gives 正如预期的那样:'你好的第一个字母是 h'

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

s = '{0} 变成 {0.upper()} 使用 .upper() 方法'.format("hello")

引发以下错误:

AttributeError: 'str' 对象没有属性 'upper()'

为什么引发的错误说我使用 upper 作为属性而不是方法?还有其他方法可以做到:

s = '{} 变成 {} with .upper() method'.format("hello","hello".upper())#gives 预期:'hello 变成 HELLO with .upper() 方法'

谢谢!

解决方案

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

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

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

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

<预><代码>>>>值 = "你好">>>getattr(value, 'upper()') # 模板引擎试图做什么回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: 'str' 对象没有属性 'upper()'>>>getattr(value, 'upper') # 实际 Python 表达式的作用<0x10e08d298处str对象的内置方法上层>>>>getattr(value, 'upper')() # 可以调用返回的对象'你好'

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

value = '你好's = f'{value} 变成 {value.upper()} 与 .upper() 方法'

演示:

<预><代码>>>>f'{value} 变为 {value.upper()} 与 .upper() 方法''hello 用 .upper() 方法变成 HELLO'

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

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'

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")

raising the following error:

AttributeError: 'str' object has no attribute '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'

Thanks!

解决方案

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 "]")*

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'

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'

Demo:

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

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

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