Python格式化字符串f-string的使用教程
作者:古明地觉 时间:2023-10-07 22:33:29
楔子
在 Python3.6 之前,格式化字符串一般会使用百分号占位符或者 format 函数,举个例子:
name = "古明地觉"
address = "地灵殿"
# 使用百分号占位符格式化字符串
print(
"我是 %s, 来自 %s" % (name, address)
) # 我是 古明地觉, 来自 地灵殿
# 使用format函数格式化字符串
print(
"我是 {}, 来自 {}".format(name, address)
) # 我是 古明地觉, 来自 地灵殿
# format 函数还支持关键字参数
print(
"我是 {name}, 来自 {address}".format(
address=address, name=name)
) # 我是 古明地觉, 来自 地灵殿
但是从 3.6 开始,Python 新增了一个格式化字符串的方法,称之为 f-string。f-string 的功能非常强大,可以说是一把 "瑞士军刀"。
name = "古明地觉"
address = "地灵殿"
print(
f"我是 {name}, 来自 {address}"
) # 我是 古明地觉, 来自 地灵殿
使用 f-string 需要给字符串增加一个前缀 f,此时 {} 和它里面的内容则不再表示字符串,而是整体作为一个需要单独计算的值或者表达式、或者变量。我们再举个例子:
print(f"1 + 1 = {1 + 1}") # 1 + 1 = 2
print(
f"sum([1, 2, 3]) = {sum([1, 2, 3])}"
) # sum([1, 2, 3]) = 6
print(
f"{'--'.join(['a', 'b', 'c', 'd'])}"
) # a--b--c--d
try:
print(f"{a}")
except Exception as e:
print(e) # name 'a' is not defined
# 在f-string中,{} 里面的内容是需要单独计算的
# 可以是常量,比如 {123}、{'hello'} 等等
# 可以是表达式,比如 {1 + 1}、{2 > 1} 等等
# 可以是变量,比如 {a}、{name},但是变量要定义好
# 而我们上面的 a 没有定义,所以报错
# 或者定义一个变量
a = lambda x: x + 100
print(f"{a}") # <function <lambda> at 0x000...>
print(f"{a(1)}") # 101
我们看到 f-string 还是很方便的,并且和 format 功能类似,但是性能要优于 format 函数。
当然 f-string 的功能远没有我们介绍的这么简单,它支持的操作非常多,下面就来逐一介绍。
实现 repr 打印
有时候我们在打印的时候需要带上引号。
name = "古明地觉"
print(name) # 古明地觉
print("%s" % name) # 古明地觉
# 如果使用 %r 打印,会带上单引号
print("%r" % name) # '古明地觉'
# 上面类似于 str 和 repr 的区别
print(str(name)) # 古明地觉
print(repr(name)) # '古明地觉'
# 等价于调用 __str__ 和 __repr__
print(name.__str__()) # 古明地觉
print(name.__repr__()) # '古明地觉'
当我们在交互式环境下,不使用 print,而是直接输入变量 name、然后回车,那么会调用 __repr__ 方法。如果使用 print(name),那么不管在什么环境,都会调用 __str__ 方法。
那么在字符串周围带上一层单引号,有什么意义呢?
birthday = "1995-07-05"
print("select name from where birthday > %s" % birthday)
print("select name from where birthday > %r" % birthday)
"""
select name from where birthday > 1995-07-05
select name from where birthday > '1995-07-05'
"""
看到区别了吗?如果是第一个查询,那么肯定是会报错的。重点来了,如何通过 f-string 实现这种效果呢?
birthday = "1995-07-05"
# 我们只需要在打印的内容后面加上一个!r即可
print(f"{birthday!r}") # '1995-07-05'
print(f"{birthday}") # 1995-07-05
# "{name}" <==> str(name) <==> name.__str__()
# "{name!r}" <==> repr(name) <==> name.__repr__()
print(f"{'.'.join(['a', 'b', 'c'])}") # a.b.c
print(f"{'.'.join(['a', 'b', 'c'])!r}") # 'a.b.c'
# 注意:!r针对的是字符串
# 虽然也可以作用于其它对象,不过没有效果
print(f"{123!r}") # 123
print(f"{3.14!r}") # 3.14
# 另外除了 !r,还有 !s 和 !a,只有这三种
# !a 和 !r 类似,!s是默认选择、加不加均可
print(f"{birthday}") # 1995-07-05
print(f"{birthday!s}") # 1995-07-05
print(f"{birthday!a}") # '1995-07-05'
print(f"{birthday!r}") # '1995-07-05'
来源:https://mp.weixin.qq.com/s/sMzBWW8ba61G5axOlWvfjw
标签:Python,格式化,字符串,f-string
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
vue+elementui+vuex+sessionStorage实现历史标签菜单的示例代码
2024-04-30 10:26:30
![](https://img.aspxhome.com/file/2023/8/130208_0s.png)
详解C#把DataTable中数据一次插入数据库的方法
2024-01-17 20:23:51
Python实现PING命令的示例代码
2022-01-10 09:19:15
![](https://img.aspxhome.com/file/2023/4/89114_0s.png)
一篇文章入门Python生态系统(Python新手入门指导)
2023-11-03 01:12:00
![](https://img.aspxhome.com/file/2023/8/101698_0s.png)
Python入门之布尔值详解
2023-01-17 06:29:58
![](https://img.aspxhome.com/file/2023/8/113108_0s.png)
Python时间序列处理之ARIMA模型的使用讲解
2021-04-10 05:53:34
![](https://img.aspxhome.com/file/2023/0/76800_0s.png)
Python如何配置环境变量详解
2021-11-20 08:18:21
![](https://img.aspxhome.com/file/2023/6/97056_0s.png)
日常整理python执行系统命令的常见方法(全)
2022-07-30 10:39:45
python操作mongodb根据_id查询数据的实现方法
2023-04-04 23:12:28
php获取文章内容第一张图片的方法示例
2023-11-09 18:55:14
php引用地址改变变量值的问题
2023-11-14 12:41:31
pycharm配置当鼠标悬停时快速提示方法参数
2022-12-07 09:24:41
![](https://img.aspxhome.com/file/2023/1/69601_0s.jpg)
python学习实操案例(四)
2023-10-12 04:43:57
![](https://img.aspxhome.com/file/2023/5/131075_0s.png)
PyTorch详解经典网络ResNet实现流程
2022-08-06 09:40:32
![](https://img.aspxhome.com/file/2023/7/101587_0s.png)
用Python绘制一个仿黑洞图像
2021-10-03 03:07:57
![](https://img.aspxhome.com/file/2023/8/127608_0s.jpg)
python查找指定依赖包简介信息实现
2023-11-02 22:04:11
你知道怎么用Python监控聊天记录吗
2021-09-12 21:58:19
![](https://img.aspxhome.com/file/2023/0/117930_0s.png)
Python QTimer实现多线程及QSS应用过程解析
2023-10-26 12:34:46
Python+PyQt5实现开发Memcached客户端
2022-04-13 13:17:48
python函数存储在模块的优点及用法总结
2023-06-03 16:52:41