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

Python 的 f 字符串或格式化字符串是格式化字符串的新方法. 此功能在 Python 3.6 中在 PEP-498 中引入。

为什么我们需要 f-strings?

Python提供各种方法来格式化一个字符串,让我们快速看看它们以及它们的问题。

  • % 格式化 - 非常适合简单的格式化,但对 strings(/community/tutorials/python-string-template)的支持有限,只有 duplicates. 我们不能使用它与对象
  • Template Strings - 它非常基本。 Template strings/python-function-arguments和参数必须是字符串
  • String() - Python String format(社区/tutorials/python-string-formate)仅被引

Python f-strings 几乎与 format() 函数相似,但删除了 format() 函数所具有的所有词汇性,让我们看看我们可以使用 f-strings 对上面的字符串进行格式化。

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

Python f-strings 被引入为字符串格式的最小语法 **. 表达式在运行时进行评估. 如果您正在使用 Python 3.6 或更高版本,您应该为您的所有字符串格式要求使用 f-strings。

Python f 字符串的例子

让我们来看看一个简单的 f 字符串的例子。

 1name = 'Pankaj'
 2age = 34
 3
 4f_string = f'My Name is {name} and my age is {age}'
 5
 6print(f_string)
 7print(F'My Name is {name} and my age is {age}')  # f and F are same
 8
 9name = 'David'
10age = 40
11
12# f_string is already evaluated and won't change now
13print(f_string)

输出:

1My Name is Pankaj and my age is 34
2My Name is Pankaj and my age is 34
3My Name is Pankaj and my age is 34

Python 执行一个接一个的陈述,一旦对 f-string 表达式进行评估,即使表达式值发生变化,它们也不会改变,这就是为什么在上面的代码片段中,f_string 值即使在名称年龄变量在该程序的后一部分发生了变化之后仍然保持不变。

1. f 字符串与表达式和转换

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

 1from datetime import datetime
 2
 3name = 'David'
 4age = 40
 5d = datetime.now()
 6
 7print(f'Age after five years will be {age+5}')  # age = 40
 8print(f'Name with quotes = {name!r}')  # name = David
 9print(f'Default Formatted Date = {d}')
10print(f'Custom Formatted Date = {d:%m/%d/%Y}')

输出:

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

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

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

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

输出:

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

3. 具有对象和属性的 f 字符串

我们也可以在f字符串中访问对象属性。

 1class Employee:
 2    id = 0
 3    name = ''
 4
 5    def __init__(self, i, n):
 6        self.id = i
 7        self.name = n
 8
 9    def __str__(self):
10        return f'E[id={self.id}, name={self.name}]'
11
12emp = Employee(10, 'Pankaj')
13print(emp)
14
15print(f'Employee: {emp}\nName is {emp.name} and id is {emp.id}')

输出:

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

f-strings 调用函数

我们也可以在 f 字符串格式化中调用函数。

1def add(x, y):
2    return x + y
3
4print(f'Sum(10,20) = {add(10, 20)}')

结果: 总数(10,20) = 30

5. 带白色空间的 f-string

如果表达式中有引导或追溯白色空间,则被忽略;如果字面字符串部分包含白色空间,则保留。

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

6. 带 f 弦的 Lambda 表达式

我们也可以使用 [lambda 表达式]( / 社区 / 教程 / python-lambda)内部f 字符串表达式。

1x = -20.45
2print(f'Lambda Example: {(lambda x: abs(x)) (x)}')
3
4print(f'Lambda Square Example: {(lambda x: pow(x, 2)) (5)}')

输出:

1Lambda Example: 20.45
2Lambda Square Example: 25

第7章 模糊的例子

让我们来看看一些 Python f 字符串的模糊的例子。

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

输出:

1quoted string
2{ 40 }
3{40}

这就是 python 格式化字符串 aka f-strings 的全部。

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

参考: PEP-498, 官方文件

Published At
Categories with 技术
comments powered by Disqus