擅长:python、mysql、java
<p><a href="https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings" rel="noreferrer">f-string</a>格式:</p>
<p>这是Python 3.6中的新特性-字符串像往常一样放在引号中,前面加上<code>f'...</code>,就像原始字符串的<code>r'...</code>一样。然后,将要放入的内容放入字符串、变量、数字、大括号内<code>f'some string text with a {variable} or {number} within that text'</code>-Python的计算结果与以前的字符串格式方法相同,只是此方法可读性更强。</p>
<pre><code>>>>a = 3.141592
>>>print(f'My number is {a:.2f} - look at the nice rounding!')
My number is 3.14 - look at the nice rounding!
</code></pre>
<p>在本例中,您可以看到我们<a href="https://docs.python.org/3/library/string.html#format-examples" rel="noreferrer">format with decimal places</a>的方式与以前的字符串格式化方法类似。</p>
<p>NB <code>a</code>可以是数字、变量,甚至是表达式,例如<code>f'{3*my_func(3.14):02f}'</code>。</p>
<p>接下来,对于新代码,应该优先使用f字符串,而不是常用的%s或str.format()方法,因为f字符串是很多<a href="https://cito.github.io/blog/f-strings/" rel="noreferrer">faster</a>。</p>