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多线程编程(三):threading.Thread类的重要函数和方法
Apr 05 Python
简单介绍Python中的JSON使用
Apr 28 Python
Python中的zipfile模块使用详解
Jun 25 Python
Python语法快速入门指南
Oct 12 Python
Python编程中的文件操作攻略
Oct 16 Python
利用python脚本如何简化jar操作命令
Feb 24 Python
python+selenium 鼠标事件操作方法
Aug 24 Python
Python操作excel的方法总结(xlrd、xlwt、openpyxl)
Sep 02 Python
django model通过字典更新数据实例
Apr 01 Python
pandas创建DataFrame的7种方法小结
Jun 14 Python
python属于解释型语言么
Jun 15 Python
Matplotlib 折线图plot()所有用法详解
Jul 28 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
PHP实现二维数组(或多维数组)转换成一维数组的常见方法总结
2019/12/04 PHP
Javascript 中介者模式实例
2009/12/16 Javascript
jQuery实现新消息在网页标题闪烁提示
2015/06/23 Javascript
js随机生成字母数字组合的字符串 随机动画数字
2015/09/02 Javascript
JavaScript直播评论发弹幕切图功能点集合效果代码
2016/06/26 Javascript
微信小程序 生命周期和页面的生命周期详细介绍
2017/01/19 Javascript
javascript 网页进度条简单实例
2017/02/22 Javascript
JavaScript数据结构之链表的实现
2017/03/19 Javascript
vue音乐播放器插件vue-aplayer的配置及其使用实例详解
2017/07/10 Javascript
关于前后端json数据的发送与接收详解
2017/07/30 Javascript
对angularJs中2种自定义服务的实例讲解
2018/09/30 Javascript
jQuery实现判断滚动条滚动到document底部的方法分析
2019/08/27 jQuery
使用Layui搭建后台管理界面的操作方法
2019/09/20 Javascript
Vue+Bootstrap实现简易学生管理系统
2021/02/09 Vue.js
Python中的Numeric包和Numarray包使用教程
2015/04/13 Python
Python 查看文件的编码格式方法
2017/12/21 Python
python2.7 json 转换日期的处理的示例
2018/03/07 Python
Python实现简单层次聚类算法以及可视化
2019/03/18 Python
详解Django中的FBV和CBV对比分析
2021/03/01 Python
H5 canvas中width、height和style的宽高区别详解
2018/11/02 HTML / CSS
HTML5+lufylegend实现游戏中的卷轴
2016/02/29 HTML / CSS
Kate Spade美国官网:纽约新兴时尚品牌,以包包闻名于世
2017/11/09 全球购物
阿联酋航空丹麦官方网站:Emirates DK
2019/08/25 全球购物
六道php面试题附答案
2014/06/05 面试题
仓管员岗位责任制
2014/02/19 职场文书
高中竞选班长演讲稿
2014/04/24 职场文书
信仰心得体会
2014/09/05 职场文书
党旗在我心中演讲稿
2014/09/15 职场文书
2014年四风问题个人对照自查剖析材料
2014/09/15 职场文书
2015年街道办事处团委工作总结
2015/10/14 职场文书
2016年安全月活动总结
2016/04/06 职场文书
php随机生成验证码,php随机生成数字,php随机生成数字加字母!
2021/04/01 PHP
Oracle以逗号分隔的字符串拆分为多行数据实例详解
2021/07/16 Oracle
PHP获取学生成绩的方法
2021/11/17 PHP
Pyhton爬虫知识之正则表达式详解
2022/04/01 Python
ant design vue的form表单取值方法
2022/06/01 Vue.js