我正在探索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>
有人可以解释为什么会这样吗?我在这里想念什么?
答案 0 :(得分:-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()}")
也可以使用,但是如果不将其与变量一起使用,则使用字符串格式有什么好处?