Python中格式化字符串的四种实现


Posted in Python onMay 26, 2020

关于Python的格式化字符串,几乎所有接触过Python语言的人都知道其中一种,即使用运算符%,但对于绝大多数初学者来说也仅此而已。

因此,本文将先总结如何通过%运算符来格式化字符串,同时指出这种方式的缺点,然后带你了解Python中另外三种强大的格式化字符串的方式:str.format()、f-string以及模板字符串,并给出在何时选择何种方式的建议。

一、%运算符格式化字符串

1. 如何使用

字符串对象都有一个使用%运算符完成的?戎貌僮鳎?杀挥美锤袷交?址??W罴虻サ娜纾?/p>

In [11]: name = "Monty Python"
In [12]: "Hello, %s." % name
Out[12]: 'Hello, Monty Python.'

如果想要对一段字符串中插入多个变量进行格式化,则需要使用一个元组将待插入变量包在一起,如:

In [14]: name = "Monty Python"

In [15]: age = 100

In [16]: "Hello, %s. You are %d years old" % (name, age)
Out[16]: 'Hello, Monty Python. You are 100 years old'

2. 缺点概述

使用%运算符的方式来格式化字符串自Python语言诞生之日起就已存在,上述代码看起来也很直观易读,但是当字符串更长,待插入变量更多,则使用%来格式化字符串的可读性将急剧下降,如:

In [23]: first_name = "Eric"

In [24]: last_name = "Idle"

In [25]: age = 100

In [26]: profession = "comedian"

In [27]: affiliation = "Monty Python"

In [28]: "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)
Out[28]: 'Hello, Eric Idle. You are 100. You are a comedian. You were a member of Monty Python.'

上述使用%格式化字符串不仅冗长,而且容易出错,因为这种方式并不够正确显示元组或者字典。

实际上,在Python官方文档中,对于使用%运算符格式化字符串这种方式的评价也是负面的:

  • The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly).使用%格式化字符串会产生一系列异常,这些异常将引起一系列常见错误(如:无法正确显示元组和字典)。
  • Using the newerformatted string literals, the str.format() interface, ortemplate strings may help avoid these errors.
  • 使用更新的格式化字符串字面量(f-string:formatted string literals),str.format()接口或者模板字符串(template strings)可以帮助避免这些错误。

Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.
当然,上述三种可替代的格式化字符串方式也都在简洁、灵活和可扩展方面有所取舍。

二、str.format()格式化字符串

1. 如何使用

str.format()是对使用%实现格式化字符串的一种改进。这种方式使用的语法和普通函数调用相差无几。

使用str.format(),字符串中待替换的域使用{}表示:

In [29]: name = "Eric"

In [30]: age = 100

In [31]: "Hello, {}. You are {}.".format(name, age)
Out[31]: 'Hello, Eric. You are 100.'

也可以通过索引的方式指定format()中哪一个变量和值应该填入哪一个{},如:

In [32]: name = "Eric"

In [33]: age = 100

In [34]: "Hello, {1}. You are {0}.".format(age, name)
Out[34]: 'Hello, Eric. You are 100.'

除了索引,也可以通过在{}中指定名称的方式来实现类似上述功能,如:

In [36]: name = "Eric"

In [37]: age = 100

In [38]: "Hello, {name}. You are {age}.".format(age=age, name=name)
Out[38]: 'Hello, Eric. You are 100.'

基于上面的方式,当待格式化的信息都来自一个字典时,Python中还有如下骚操作:

In [39]: person = {'name': 'Eric', 'age': 100}

In [40]: "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
Out[40]: 'Hello, Eric. You are 100.'

更骚的是,上面的骚操作还能利用字典拆包**进一步简化:

In [41]: person = {'name': 'Eric', 'age': 100}

In [42]: "Hello, {name}. You are {age}.".format(**person)
Out[42]: 'Hello, Eric. You are 100.'

2. 缺点概述

相较于%运算符方式,使用str.format()已经使得格式化字符串语法更加可读,但是当变量增多时,这种方式写出的程序也会显得很冗长:

In [43]: first_name = "Eric"

In [44]: last_name = "Idle"

In [45]: age = 74

In [46]: profession = "comedian"

In [47]: affiliation = "Monty Python"

In [48]: print(("Hello, {first_name} {last_name}. You are {age}. " +
  ...: "You are a {profession}. You were a member of {affiliation}.") \
  ...: .format(first_name=first_name, last_name=last_name, age=age, \
  ...: profession=profession, affiliation=affiliation))
Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.

三、f-string格式化字符串

在Python 3.6中f-string被引入(具体请见PEP 498),也被称作格式化字符串字面量(formatted string literals)。

f-string是字符串字面量,且其以字母f开头,{}中包含变量或表达式,变量或表达式将在运行(runtime)时通过使用__format__协议被替换成具体的值。

1. 如何使用

简单的f-string格式化字符串如:

In [49]: name = "Eric"

In [50]: age = 100

In [51]: f"Hello, {name}. You are {age}."
Out[51]: 'Hello, Eric. You are 100.'

如前所述,{}中除接受变量外,还接受表达式,如:

In [52]: f"{2 * 37}"
Out[52]: '74'

f-string更强大的地方在于,{}中接受函数调用:

In [53]: def to_lowercase(input):
  ...:   return input.lower()
  ...: 

In [54]: name = "Eric Idle"

In [55]: f"{to_lowercase(name)} is funny."
Out[55]: 'eric idle is funny.'

甚至,你可以对创建于类的对象使用f-string,如:

class Comedian:
  def __init__(self, first_name, last_name, age):
    self.first_name = first_name
    self.last_name = last_name
    self.age = age

  def __str__(self):
    return f"{self.first_name} {self.last_name} is {self.age}."

  def __repr__(self):
    return f"{self.first_name} {self.last_name} is {self.age}. Surprise!"


def main():
  new_comedian = Comedian("Eric", "Idle", "74")
  print(f"{new_comedian}")


if __name__ == '__main__':
  main()

上述代码的输出为:

Eric Idle is 74.

四、Template类格式化字符串

五、参考资料

[1] Python 3's f-Strings: An Improved String Formatting Syntax (Guide)
[2] Python String Formatting Best Practices

到此这篇关于Python中格式化字符串的四种实现的文章就介绍到这了,更多相关Python格式化字符串内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python中文编码那些事
Jun 25 Python
简要讲解Python编程中线程的创建与锁的使用
Feb 28 Python
Python使用文件锁实现进程间同步功能【基于fcntl模块】
Oct 16 Python
python实现log日志的示例代码
Apr 28 Python
python自带tkinter库实现棋盘覆盖图形界面
Jul 17 Python
使用Python和OpenCV检测图像中的物体并将物体裁剪下来
Oct 30 Python
pytorch的batch normalize使用详解
Jan 15 Python
基于Tensorflow高阶读写教程
Feb 10 Python
Python通过Pillow实现图片对比
Apr 29 Python
在pycharm中使用matplotlib.pyplot 绘图时报错的解决
Jun 01 Python
如何用python清洗文件中的数据
Jun 18 Python
Python可视化动图组件ipyvizzu绘制惊艳的可视化动图
Apr 21 Python
使用tensorflow实现VGG网络,训练mnist数据集方式
May 26 #Python
浅谈Tensorflow加载Vgg预训练模型的几个注意事项
May 26 #Python
Tensorflow加载Vgg预训练模型操作
May 26 #Python
PyQt5如何将.ui文件转换为.py文件的实例代码
May 26 #Python
TensorFlow实现模型断点训练,checkpoint模型载入方式
May 26 #Python
python 日志模块 日志等级设置失效的解决方案
May 26 #Python
python3.7+selenium模拟淘宝登录功能的实现
May 26 #Python
You might like
ADODB的数据库封包程序库
2006/12/31 PHP
使用dump函数,给php加断点测试
2013/06/25 PHP
PHP SFTP实现上传下载功能
2017/07/26 PHP
ArrayList类(增强版)
2007/04/04 Javascript
JS getMonth()日期函数的值域是0-11
2010/02/15 Javascript
利用jquery操作select下拉列表框的代码
2010/06/04 Javascript
js复制到剪切板的实例方法
2013/06/28 Javascript
js抽奖实现随机抽奖代码效果
2013/12/02 Javascript
仿百度联盟对联广告实现代码
2014/08/30 Javascript
JavaScript的内存释放问题详解
2015/01/21 Javascript
javascript 闭包详解
2015/07/02 Javascript
基于jQuery实现的查看全文功能【实用】
2016/12/11 Javascript
js排序与重组的实例讲解
2017/08/28 Javascript
解决html-jquery/js引用外部图片时遇到看不了或出现403的问题
2017/09/22 jQuery
nodejs实现截取上传视频中一帧作为预览图片
2017/12/10 NodeJs
在vue项目中使用Jquery-contextmenu插件的步骤讲解
2019/01/27 jQuery
详解vue-element Tree树形控件填坑路
2019/03/26 Javascript
JS实现根据详细地址获取经纬度功能示例
2019/04/16 Javascript
记一次vue跨域的解决
2020/10/21 Javascript
[02:29]完美世界高校联赛上海赛区回顾
2015/12/15 DOTA
Python实现批量把SVG格式转成png、pdf格式的代码分享
2014/08/21 Python
python刷投票的脚本实现代码
2014/11/08 Python
python实现将内容分行输出
2015/11/05 Python
Django app配置多个数据库代码实例
2019/12/17 Python
pytorch逐元素比较tensor大小实例
2020/01/03 Python
Kenneth Cole官网:纽约时尚优雅品牌
2016/11/14 全球购物
GC是什么?为什么要有GC?
2013/12/08 面试题
大一学生的职业生涯规划书范文
2014/01/19 职场文书
仓管员岗位责任制
2014/02/19 职场文书
建筑投标担保书
2014/05/20 职场文书
个人典型事迹材料
2014/12/30 职场文书
React forwardRef的使用方法及注意点
2021/06/13 Javascript
MySQL里面的子查询的基本使用
2021/08/02 MySQL
浅谈Redis缓冲区机制
2022/06/05 Redis
Java实现HTML转为Word的示例代码
2022/06/28 Java/Android
win10蓝屏0xc0000001安全模式进不了怎么办?win10出现0xc0000001的解决方法
2022/08/05 数码科技