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 和 F 是相同的
    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-strings 表达式被求值,即使表达式的值发生变化,它们也不会改变。这就是为什么在上面的代码片段中,即使在程序的后半部分’name’和’age’变量发生了变化,f_string 的值仍然保持不变。

    1. f-strings 与表达式和转换

    我们可以使用 f-strings 将日期时间转换为特定格式。我们还可以在 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-string

    如果表达式中有前导或尾随空格,则它们将被忽略。如果字面字符串部分包含空格,则它们将被保留。

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

    6. 带有 f-string 的 Lambda 表达式

    我们也可以在 f-string 表达式中使用 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-string 的其他例子

    让我们看一些 Python f-string 的其他例子。

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

    输出:

    quoted string
    { 40 }
    {40}
    

    这就是关于 Python 格式化字符串(即 f-strings)的全部内容。

    您可以从我们的 GitHub 仓库中查看完整的 Python 脚本和更多 Python 示例。

    参考:PEP-498,官方文档