Python f字符串– PEP 498 –文字字符串插值
Python f字符串或者格式化的字符串是格式化字符串的新方法。
此功能是在PEP-498下的Python 3.6中引入的。
也称为文字字符串内插。
为什么我们需要F字符串?
Python提供了多种格式化字符串的方法。
让我们快速查看它们以及它们有什么问题。
%格式-非常适合简单格式设置,但仅支持字符串,整数和双精度。
我们不能将其与对象一起使用。模板字符串–非常基础。
模板字符串仅可与关键字参数(例如字典)一起使用。
我们不允许调用任何函数,并且参数必须是字符串。字符串格式()– Python字符串格式()函数被引入,以克服%格式和模板字符串的问题和有限的功能。
但是,它太冗长了。
让我们用一个简单的例子来看看它的详细程度。
Python f字符串的工作原理几乎类似于format()函数,但删除了format()函数具有的所有冗长性。
让我们看看使用f字符串格式化上面的字符串有多么容易。
>>> age = 4 * 10 >>> 'My age is {age}.'.format(age=age) 'My age is 40.'
引入Python f-strings以使字符串格式化的语法最少。
在运行时评估表达式。
如果使用的是Python 3.6或者更高版本,则应使用f-strings满足所有字符串格式要求。
Python f字符串示例
让我们看一个简单的f字符串示例。
>>> f'My age is {age}' 'My age is 40.'
输出:
name = 'hyman' 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)
Python会一一执行语句,一旦评估了f字符串表达式,即使表达式值更改,它们也不会更改。
因此,在上面的代码段中,即使在程序的后半部分更改了"名称"和"年龄"变量之后,f_string值仍保持不变。
1.带表达式和转换的f字符串
我们可以使用f字符串将日期时间转换为特定格式。
我们还可以在f字符串中运行数学表达式。
My Name is hyman and my age is 34 My Name is hyman and my age is 34 My Name is hyman and my age is 34
输出:
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}')
2. f字符串支持原始字符串
我们也可以使用f字符串创建原始字符串。
Age after five years will be 45 Name with quotes = 'David' Default Formatted Date = 2016-10-10 11:47:12.818831 Custom Formatted Date = 10/10/2016
输出:
print(f'Default Formatted Date:\n{d}') print(fr'Default Formatted Date:\n {d}')
3.具有对象和属性的f字符串
我们也可以使用f字符串访问对象属性。
Default Formatted Date: 2016-10-10 11:47:12.818831 Default Formatted Date:\n 2016-10-10 11:47:12.818831
输出:
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, 'hyman') print(emp) print(f'Employee: {emp}\nName is {emp.name} and id is {emp.id}')
4. f字符串调用函数
我们也可以用f字符串格式调用函数。
E[id=10, name=hyman] Employee: E[id=10, name=hyman] Name is hyman and id is 10
输出:Sum(10,20)= 30
5.带空格的f字符串
如果表达式中存在前导或者尾随空格,则将其忽略。
如果文字字符串部分包含空格,则将保留它们。
def add(x, y): return x + y print(f'Sum(10,20) = {add(10, 20)}')
6.带f字符串的Lambda表达式
我们也可以在字符串表达式内部使用lambda表达式。
>>> age = 4 * 20 >>> f' Age = { age } ' ' Age = 80 '
输出:
x = -20.45 print(f'Lambda Example: {(lambda x: abs(x)) (x)}') print(f'Lambda Square Example: {(lambda x: pow(x, 2)) (5)}')
7. f字符串的其他示例
让我们看一些Python f字符串的其他示例。
Lambda Example: 20.45 Lambda Square Example: 25
输出:
print(f'{"quoted string"}') print(f'{{ {4*10} }}') print(f'{{{4*10}}}')
这就是python格式的字符串,又称f字符串。