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,官方文档

相关推荐

  1. Python f-strings - PEP 498 - 字面字符串

    2024-02-06 21:00:03       27 阅读
  2. Scala的字符串

    2024-02-06 21:00:03       6 阅读
  3. python查找

    2024-02-06 21:00:03       33 阅读
  4. Python——用新字符替换字符串中的旧字符

    2024-02-06 21:00:03       8 阅读
  5. 找到字符串中所有字母异位词(LeetCode 438

    2024-02-06 21:00:03       35 阅读
  6. 438 找到字符串中所有字母异味词

    2024-02-06 21:00:03       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-06 21:00:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-06 21:00:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-06 21:00:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-06 21:00:03       18 阅读

热门阅读

  1. SQL--DML

    SQL--DML

    2024-02-06 21:00:03      28 阅读
  2. PostgreSQL导出导入

    2024-02-06 21:00:03       33 阅读
  3. 抖音ip地址可以改?抖音如何改ip地址

    2024-02-06 21:00:03       30 阅读
  4. 重学 VUE —— 一、创建一个应用

    2024-02-06 21:00:03       28 阅读
  5. SpringBoot 动态加载jar包,动态配置

    2024-02-06 21:00:03       28 阅读
  6. 什么是边缘计算?

    2024-02-06 21:00:03       35 阅读
  7. Spring Boot项目整合Seata AT模式

    2024-02-06 21:00:03       31 阅读
  8. c#directory 和directoryinfo的使用

    2024-02-06 21:00:03       27 阅读
  9. 微服务限流(漏桶算法、令牌桶算法)

    2024-02-06 21:00:03       35 阅读