【问题标题】:Format string attributes [duplicate]格式字符串属性[重复]
【发布时间】:2019-11-14 22:13:10
【问题描述】:

我在 python 中探索格式字符串时遇到了使用整数来识别位置参数的手动字段规范。

据我所知,格式字符串只支持两个运算符:. (getattr) 和 [] (getitem)

但是当我尝试使用它时,我得到了一个错误。

"The story of a {0} {1.upper()}".format("cunning", "fox")

这给了

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

但是,当我这样做时:

"The story of a {0} {1.upper}".format("cunning", "fox")

它给出了输出: The story of a cunning <built-in method upper of str object at 0x7f65756e1e18>

有人能解释一下为什么会这样吗?我在这里错过了什么?

【问题讨论】:

    标签: python python-3.x format-string


    【解决方案1】:

    使用 Python 3.6 中引入的新 f-strings。如果你现在正在学习 Python,那是你最好的选择。

    a = "cunning"
    b = "fox"
    print(f"The story of a {a} {b.upper()}")
    

    print(f"The story of a {'cunning'} {'fox'.upper()}") 也可以,但是如果你不将它与变量一起使用,那么使用字符串格式化有什么好处呢?

    【讨论】:

    • 然而,这不是问题的答案
    • 感谢您的回答。我知道f-strings 并且不是在寻找解决方法。这个问题只是针对这个用例,为什么python会抛出那个错误,当它可以找出存在一个内置函数时。
    猜你喜欢
    • 2011-07-22
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2016-11-23
    • 2020-11-21
    • 2021-09-06
    相关资源
    最近更新 更多