设置字符串属性格式

2024-10-04 01:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中研究格式字符串,遇到了用整数来标识位置参数的手动字段规范。你知道吗

据我所知,format string只支持两个操作符:.(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>

有人能解释一下为什么会这样吗?我错过了什么?你知道吗


Tags: ofthe字符串format参数object格式整数
1条回答
网友
1楼 · 发布于 2024-10-04 01:31:06

使用python3.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()}")也可以,但是如果不使用变量,那么使用字符串格式有什么好处呢?你知道吗

相关问题 更多 >