AttributeError:“ str”对象没有属性“ title()”

时间:2019-11-12 05:01:39

标签: python-3.x

first="harry"
last="potter"

print(first, first.title())
print(f"Full name: {first.title()} {last.title()}")
print("Full name: {0.title()} {1.title()}".format(first, last))

前两个语句工作正常;这意味着'str'对象具有属性title()。 第三打印语句给出错误。为什么会这样?

2 个答案:

答案 0 :(得分:0)

str.format()语法与f字符串语法不同。特别是,虽然f字符串实际上使您可以将任何表达式放在方括号之间,但str.format()的局限性要大得多。 Per the documentation

  

替换字段的语法如下:

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | digit+]
attribute_name    ::=  identifier
element_index     ::=  digit+ | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  <described in the next section>

您会注意到,虽然属性名称(通过点运算符.)和索引(通过方括号[])-换句话说,-有效,实际的方法调用(或任何其他表达式)无效。我推测这是因为str.format()实际上并不执行文本,而只是交换已经存在的对象。


实际的f字符串(第二个示例)与str.format()方法具有相似的语法,因为它们使用大括号{}表示要替换的区域,但根据{{3 }},

  

F字符串提供了一种使用最小语法在字符串文字中嵌入表达式的方法。应该注意的是,f字符串实际上是在运行时评估的表达式,而不是恒定值。

这显然与str.format()不同(更复杂),后者更像是简单的文本替换-f字符串是一个表达式,因此被执行,并且允许在其方括号内使用完整的表达式(实际上,您甚至可以将f字符串彼此嵌套在一起,这很有趣。)

答案 1 :(得分:0)

str.format() 在相应的占位符中传递字符串对象。通过使用“ ”,您可以访问字符串属性或功能。这就是 {0.title()} 在字符串类中搜索特定方法的原因,而 title()一无所获。

但是,如果您使用

print("Full name: {0.title} {1.title}".format(first, last))

>> Full name: <built-in method title of str object at 0x7f5e42d09630><built-in method title of str object at 0x7f5e42d096b0>

在这里您可以看到您可以访问字符串的内置方法

如果您想将 title() format() 一起使用,请按以下方式使用:

print("Full name: {0} {1}".format(first.title(), last.title()))

>> Full name: Harry Potter