使用format()函数提高对Python格式的理解

2024-04-25 02:06:13 发布

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

hilarious = False

joke_evaluation = "Isn't that joke so funny?! {}"

print(joke_evaluation.format(hilarious))

对于下面几行Python代码,我无法理解一个关键概念。你知道吗

一个字符串被分配给变量joke_evaluation并包含{},以便在其中嵌入另一个变量。你知道吗

第三行代码让我陷入了困境,我们说打印变量joke_evaluation,然后使用.format()函数并将另一个变量传递给它hilarious,它被设置为布尔数据类型。你知道吗

{}是否有效地充当占位符?.format()函数如何知道用变量hilarious填充{}?你知道吗

如果可能的话,请用基本的术语来解释以增加我的理解,我无法理解Python如何填充上面提到的花括号{}。你知道吗


Tags: 函数字符串代码falseformat概念sothat
3条回答

阅读关于字符串的Python文档:https://docs.python.org/3.6/library/string.html?highlight=formatting

:)你需要知道的一切。您还可以更改Python版本并查看格式化的行为。你知道吗

向下滚动查看示例和说明。你知道吗

是的,{}作为占位符,它被.format方法以特殊的方式处理。你知道吗

How does the .format() function know to populate the {} with the variable hilarious?

如果您只提供{},那么它是按位置替换的,即

>>> 'first: {}, second: {}'.format(1, 2)
'first: 1, second: 2'

对于更详细或可重用的替换,可以使用命名参数:

>>> "{actor1} tells {actor2} that he's {actor1}".format(actor1='Bob', actor2='Joel')
"Bob tells Joel that he's Bob"

更多精彩的字符串格式:pyformat.info

在格式化方面,当.format用一些对象替换占位符时,它会调用^{}方法

  1. 接受格式化规范-这使您能够控制如何转换它(例如,'{:.2f}'.format(3.1415)
  2. 返回str,它将实际替换占位符

以下是我对format方法的理解:

任何带有大括号{}的字符串都将替换为您提供的变量。所以,如果我有一个字符串说:

myStr = "hello {}"

然后做:

res = myStr.format("user")
print(res) #prints "hello user" without quotes.

现在,这样做:

res = myStr.format(123123)
print(res) #prints "hello 123123" without quotes.

正如您可能猜到的,整数123123在被包含在字符串中之前被隐式转换为字符串。你知道吗

现在来看卷曲部分:

  1. 可以有多个大括号,并且传递给format方法的参数数必须相同。如: myStr = "hello {},{},{}, nice meeting you" res = myStr.format("abcd",123,"lol") print(res) #prints "hello abcd,123,lol, nice meeting you"
  2. 您甚至可以在{}中放置索引来指示位置,如{0}{1}。你知道吗

相关问题 更多 >