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

Python f-strings or formatted strings are a new method for string formatting. This functionality was introduced in Python 3.6 through PEP-498, also known as literal string interpolation.

我们为什么需要f-strings?

Python提供了多种格式化字符串的方法。让我们快速浏览一下它们以及它们可能遇到的问题。

  • % formatting – great for simple formatting but limited support for strings, ints, doubles only. We can’t use it with objects.
  • Template Strings – it’s very basic. Template strings work with keyword arguments like dictionary only. We are not allowed to call any function and arguments must be strings.
  • String format() – Python String format() function was introduced to overcome the issues and limited features of %-formatting and template strings. However, it’s too verbose. Let’s look at its verbosity with a simple example.
    >>> 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字符串示例

让我们来看一个关于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 is already evaluated and won't change now
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表达式被评估,即使表达式值发生变化,它们也不会改变。这就是为什么在上述代码片段中,即使在程序的后半部分’姓名’和’年龄’变量已经改变,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字符串调用函数

我们可以在 f-strings 格式化中调用函数。

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


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

输出:求和(10,20)= 30

5. 带空格的f字符串.

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

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

6. 使用f-字符串的Lambda表达式 xǔ f-zífù de 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-字符串的其他例子

让我们看一些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,官方文档。

发表回复 0

Your email address will not be published. Required fields are marked *


广告
将在 10 秒后关闭
bannerAds