Python f-strings – PEP 498 – 字符串插值

Python f-strings或格式化字符串是格式化字符串的新方式。此功能在Python 3.6中引入,遵循PEP-498。它也被称为字面字符串插值

为什么我们需要f-strings?

Python提供了各种格式化字符串的方法。让我们快速浏览一下它们以及它们存在的问题。

  • %格式化 – 适用于简单格式化,但对字符串、整数、浮点数的支持有限。我们无法将其用于对象。

  • 模板字符串 – 它非常基础。模板字符串仅适用于像字典这样的关键字参数。不允许调用任何函数,而且参数必须是字符串。

  • 字符串format() – Python字符串format()函數引入以解決%-格式化和模板字符串的問題和功能有限的問題。然而,它太冗長了。讓我們通過一個簡單的示例來看一下它的冗長性。

    >>> age = 4 * 10
    >>> 'My age is {age}.'.format(age=age)
    'My age is 40.'
    

Python f-strings幾乎與format()函數相似,但消除了format()函數的所有冗長性。讓我們看看如何使用f-strings輕鬆地對上述字符串進行格式化。

>>> f'My age is {age}'
'My age is 40.'

Python f-strings引入了最小的語法進行字符串格式化。表達式在運行時進行評估。如果您使用的是Python 3.6或更高版本,則應使用f-strings來滿足所有字符串格式化的需求。

Python f-strings 示例

让我们看一个简单的f-strings示例。

name = 'Pankaj'
age = 34

f_string = f'My Name is {name} and my age is {age}'

print(f_string)
print(F'My Name is {name} and my age is {age}')  # f and F are same

name = 'David'
age = 40

# f_string已经评估过,现在不会改变
print(f_string)

输出:

My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34

Python逐一执行语句,一旦评估了f-string表达式,即使表达式的值发生变化,它们也不会改变。这就是为什么在上述代码片段中,即使在程序的后半部分’name’和’age’变量发生变化后,f_string的值仍然保持不变的原因。

1. 具有表达式和转换的f-strings

我们可以使用f-strings将datetime转换为特定格式。我们还可以在f-strings中运行数学表达式。

from datetime import datetime

name = 'David'
age = 40
d = datetime.now()

print(f'Age after five years will be {age+5}')  # age = 40
print(f'Name with quotes = {name!r}')  # name = David
print(f'Default Formatted Date = {d}')
print(f'Custom Formatted Date = {d:%m/%d/%Y}')

输出:

Age after five years will be 45
Name with quotes = 'David'
Default Formatted Date = 2018-10-10 11:47:12.818831
Custom Formatted Date = 10/10/2018

2. f-strings支持原始字符串

我们也可以使用f-strings创建原始字符串。

print(f'Default Formatted Date:\n{d}')
print(fr'Default Formatted Date:\n {d}')

输出:

Default Formatted Date:
2018-10-10 11:47:12.818831
Default Formatted Date:\n 2018-10-10 11:47:12.818831

3. 使用對象和屬性的 f-strings

我們也可以在 f-strings 中訪問對象屬性。

class Employee:
    id = 0
    name = ''

    def __init__(self, i, n):
        self.id = i
        self.name = n

    def __str__(self):
        return f'E[id={self.id}, name={self.name}]'


emp = Employee(10, 'Pankaj')
print(emp)

print(f'Employee: {emp}\nName is {emp.name} and id is {emp.id}')

輸出:

E[id=10, name=Pankaj]
Employee: E[id=10, name=Pankaj]
Name is Pankaj and id is 10

4. f-strings 調用函數

我們也可以在 f-strings 格式化中調用函數。

def add(x, y):
    return x + y


print(f'Sum(10,20) = {add(10, 20)}')

輸出:Sum(10,20) = 30

5. 具有空格的 f-strings

如果表達式中存在前導或尾隨空格,則將其忽略。如果文字字符串部分包含空格,則它們將被保留。

>>> age = 4 * 20
>>> f'   Age = {  age   }  '
'   Age = 80  '

6. 使用 f-strings 的 Lambda 表達式

我們也可以在 f-strings 表達式中使用 lambda 表達式。

x = -20.45
print(f'Lambda Example: {(lambda x: abs(x)) (x)}')

print(f'Lambda Square Example: {(lambda x: pow(x, 2)) (5)}')

輸出:

Lambda Example: 20.45
Lambda Square Example: 25

7. f-strings miscellaneous examples

讓我們看一些 Python f-strings 的其他例子。

print(f'{"quoted string"}')
print(f'{{ {4*10} }}')
print(f'{{{4*10}}}')

輸出:

quoted string
{ 40 }
{40}

這就是關於 Python 格式化字串(即 f-strings)的全部。

您可以從我們的 GitHub 存儲庫檢查完整的 Python 腳本和更多 Python 示例。

參考:PEP-498官方文檔

Source:
https://www.digitalocean.com/community/tutorials/python-f-strings-literal-string-interpolation