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读写Redis数据库操作示例
Mar 18 Python
以911新闻为例演示Python实现数据可视化的教程
Apr 23 Python
python安装与使用redis的方法
Apr 19 Python
python+splinter实现12306网站刷票并自动购票流程
Sep 25 Python
Python OpenCV对本地视频文件进行分帧保存的实例
Jan 08 Python
django settings.py 配置文件及介绍
Jul 15 Python
python如何统计代码运行的时长
Jul 24 Python
如何在Django项目中引入静态文件
Jul 26 Python
Python远程开发环境部署与调试过程图解
Dec 09 Python
python opencv实现信用卡的数字识别
Jan 12 Python
Python实现转换图片背景颜色代码
Apr 30 Python
Python爬虫之Selenium鼠标事件的实现
Dec 04 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
老照片 - 几十年前的收音机与人
2021/03/02 无线电
咖啡是不是喝了会上瘾?咖啡是必须品吗!
2021/03/04 新手入门
PHP.MVC的模板标签系统(四)
2006/09/05 PHP
PHP字符转义相关函数小结(php下的转义字符串)
2007/04/12 PHP
PHP开启gzip页面压缩实例代码
2010/03/11 PHP
ThinkPHP整合百度Ueditor图文教程
2014/10/21 PHP
php使用sql server验证连接数据库的方法
2014/12/25 PHP
apache集成php7.3.5的详细步骤
2019/06/20 PHP
JavaScript中常见陷阱小结
2010/04/27 Javascript
jQuery之按钮组件的深入解析
2013/06/19 Javascript
JS实现的3D拖拽翻页效果代码
2015/10/31 Javascript
vue.js 初体验之Chrome 插件开发实录
2017/05/13 Javascript
JS简单实现父子窗口传值功能示例【未使用iframe框架】
2017/09/20 Javascript
windows系统下更新nodejs版本的方案
2017/11/24 NodeJs
原生JavaScript实现的简单放大镜效果示例
2018/02/07 Javascript
vee-validate vue 2.0自定义表单验证的实例
2018/08/28 Javascript
利用Promise自定义一个GET请求的函数示例代码
2019/03/20 Javascript
Webpack设置环境变量的一些误区详解
2019/12/19 Javascript
使用JavaScript获取Django模板指定键值数据
2020/05/27 Javascript
详解vue中使用transition和animation的实例代码
2020/12/12 Vue.js
[06:06]2018DOTA2亚洲邀请赛主赛事第四日战况回顾 全明星赛欢乐上演
2018/04/07 DOTA
Django在Win7下的安装及创建项目hello word简明教程
2014/07/14 Python
wxPython中listbox用法实例详解
2015/06/01 Python
python OpenCV学习笔记之绘制直方图的方法
2018/02/08 Python
python分布式编程实现过程解析
2019/11/08 Python
Python时间差中seconds和total_seconds的区别详解
2019/12/26 Python
django迁移文件migrations的实现
2020/03/31 Python
python中导入 train_test_split提示错误的解决
2020/06/19 Python
OpenCV+Python3.5 简易手势识别的实现
2020/12/21 Python
css3制作动态进度条以及附加jQuery百分比数字显示
2012/12/13 HTML / CSS
马来西亚与新加坡长途巴士售票网站:BusOnlineTicket.com
2018/11/05 全球购物
挂科检讨书范文
2014/02/20 职场文书
仓库管理员岗位职责
2014/03/19 职场文书
评先进个人材料
2014/12/29 职场文书
部队个人年终总结
2015/03/02 职场文书
Android基础入门之dataBinding的简单使用教程
2022/06/21 Java/Android