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-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-strings其他示例

让我们看一些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