擅长:python、mysql、java
<p>您在第8-9行看到的内容称为<em>格式化字符串文本</em>或<em>f-strings</em>。它们在3.6版中被添加到Python中,并在<a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow noreferrer">PEP498</a>中进行了详细说明。它们基本上允许您直接在字符串中嵌入表达式。在</p>
<blockquote>
<p>What['s] the point of using line 8 and line 9 if we can just use line 10?</p>
</blockquote>
<p>那么,在对<code>print</code>的正常调用中使用它们的意义是什么?在上面的例子中,不多。当您需要使用多个值格式化字符串时,真正的好处就显现出来了。您可以直接使用变量的名称或在字符串中包含表达式,而不是执行一系列字符串连接:</p>
<pre><code>>>> a = 12
>>> b = 6
>>> f'The sum of 12 and 6 is: {a + b}'
'The sum of 12 and 6 is: 18'
>>> name = 'Bob'
>>> age = 32
>>> f'Hi. My name is {name} and my age is {age}'
'Hi. My name is Bob and my age is 32'
>>> def fib(n):
if n <= 1:
return 1
return fib(n - 1) + fib(n - 2)
>>> f'The Fibonacci number of 10 is: {fib(10)}'
'The Fibonacci number of 10 is: 89'
</code></pre>
<p>虽然从上面的例子中很难判断出是什么,但f-串非常强大。能够将整个表达式嵌入到字符串文本中是一个非常有用的特性,也可以使代码更加清晰和简洁。当您开始编写更多的代码并且代码的用例变得非常重要时,这一点将变得非常清楚。在</p>