详解Python3 中的字符串格式化语法


Posted in Python onJanuary 15, 2020

一、旧式的字符串格式化

% 操作符

参考以下示例:

>>> name = "Eric"
>>> "Hello, %s." % name
'Hello, Eric.'

当有多个变量需要插入到字符串中时:

>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello, Eric. You are 74.'

当需要替换的变量进一步增多时,使用 % 操作符格式化字符串会导致代码可读性变得很差:

>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

str.format()

str.format() 是对 % 方式的改进,它使用常见的函数调用的语法,并且可以通过定义对象本身的 __format__() 方法控制字符串格式化的具体行为。

基本用法:

>>> name = "Eric"
>>> age = 74
>>> "Hello, {}. You are {}.".format(name, age)
'Hello, Eric. You are 74.'

str.format() 相对于 % 操作符有着更强的灵活性。比如可以通过数字索引来关联替换到字符串中的变量:

>>> name = "Eric"
>>> age = 74
>>> "Hello, {1}. You are {0}.".format(age, name)
'Hello, Eric. You are 74.'

为了提高代码可读性, {} 中也可以使用有具体含义的参数名:

>>> name = "Eric"
>>> age = 74
>>> "Hello, {name}. You are {age}".format(name=name, age=age)
'Hello, Eric. You are 74'

针对字典结构的数据:

>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
'Hello, Eric. You are 74.'

或者更简洁的方式:

>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(**person)
'Hello, Eric. You are 74.'

问题在于当需要替换的变量很多时, str.format() 方式依然会导致代码变得过于冗长:

>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "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

基本用法

>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'

嵌入表达式

>>> f"{2 * 37}"
'74'

>>> def to_lowercase(input):
...  return input.lower()
 
>>> name = "Eric Idle"
>>> f"{to_lowercase(name)} is funny"
'eric idle is funny'

>>> f"{name.lower()} is funny"
'eric idle is funny'

f-string 中还可以直接嵌入某个对象实例,只要其内部实现了 __str__ 或者 __repr__ 方法:

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}"


new_comedian = Comedian("Eric", "Idle", 74)
print(f"{new_comedian}")
# Eric Idle is 74
多行 f-string
>>> name = "Eric"
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> message = (
...  f"Hi {name}. "
...  f"You are a {profession}. "
...  f"You were in {affiliation}."
... )
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'

总结

以上所述是小编给大家介绍的Python3 中的字符串格式化语法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Python 相关文章推荐
Python中编写ORM框架的入门指引
Apr 29 Python
Python代码缩进和测试模块示例详解
May 07 Python
Puppeteer使用示例详解
Jun 20 Python
python常用排序算法的实现代码
Nov 08 Python
Django admin禁用编辑链接和添加删除操作详解
Nov 15 Python
wxPython窗体拆分布局基础组件
Nov 19 Python
通过实例了解Python str()和repr()的区别
Jan 17 Python
关于Python 中的时间处理包datetime和arrow的方法详解
Mar 19 Python
Python实现从N个数中找到最大的K个数
Apr 02 Python
详解使用Python写一个向数据库填充数据的小工具(推荐)
Sep 11 Python
Django项目在pycharm新建的步骤方法
Mar 02 Python
Pytorch中Softmax与LogSigmoid的对比分析
Jun 05 Python
用pytorch的nn.Module构造简单全链接层实例
Jan 14 #Python
pytorch三层全连接层实现手写字母识别方式
Jan 14 #Python
Python实现bilibili时间长度查询的示例代码
Jan 14 #Python
基于python监控程序是否关闭
Jan 14 #Python
关于pytorch中全连接神经网络搭建两种模式详解
Jan 14 #Python
使用Pytorch来拟合函数方式
Jan 14 #Python
pytorch 模拟关系拟合——回归实例
Jan 14 #Python
You might like
谈一谈收音机的高放电路
2021/03/02 无线电
浅谈使用PHP开发微信支付的流程
2015/10/04 PHP
深入理解PHP原理之执行周期分析
2016/06/01 PHP
js动态在form上插入enctype=multipart/form-data的问题
2012/05/24 Javascript
js 剪切板应用clipboardData详细解析
2013/12/17 Javascript
jQuery性能优化技巧分析
2015/02/20 Javascript
jQuery实现向下滑出的平滑下拉菜单效果
2015/08/21 Javascript
javascript返回顶部的按钮实现方法
2016/01/09 Javascript
Bootstrap布局组件应用实例讲解
2016/02/17 Javascript
jQuery插件FusionCharts绘制2D环饼图效果示例【附demo源码】
2017/04/10 jQuery
Vue.2.0.5实现Class 与 Style 绑定的实例
2017/06/20 Javascript
用JS编写一个函数,返回数组中重复出现过的元素(实例)
2017/09/14 Javascript
微信小程序使用radio显示单选项功能【附源码下载】
2017/12/11 Javascript
jQuery实现图片简单轮播功能示例
2018/08/13 jQuery
浅谈Vue项目骨架屏注入实践
2019/08/05 Javascript
在vue中实现嵌套页面(iframe)
2020/07/30 Javascript
在Django的模型中执行原始SQL查询的方法
2015/07/21 Python
python3中set(集合)的语法总结分享
2017/03/24 Python
Python微医挂号网医生数据抓取
2019/01/24 Python
pandas 数据索引与选取的实现方法
2019/06/21 Python
Python使用grequests(gevent+requests)并发发送请求过程解析
2019/09/25 Python
Python 类的魔法属性用法实例分析
2019/11/21 Python
基于python实现查询ip地址来源
2020/06/02 Python
Numpy中np.max的用法及np.maximum区别
2020/11/27 Python
CSS3实现点击放大的动画实例代码
2017/02/27 HTML / CSS
澳大利亚领先的美容护肤品零售商之一:SkincareStore
2018/01/22 全球购物
Pamela Love官网:纽约设计师Pamela Love的精美、时尚和穿孔珠宝
2020/10/19 全球购物
JAVA招聘远程笔试题
2015/07/23 面试题
既然说Ruby中一切都是对象,那么Ruby中类也是对象吗
2013/01/26 面试题
买房协议书
2014/04/11 职场文书
学校综治宣传月活动总结
2014/07/02 职场文书
“六查”、“三学”、“三干”查摆问题整改措施
2014/09/27 职场文书
2014年医院工作总结
2014/11/20 职场文书
会议新闻稿
2015/07/17 职场文书
大学生干部培训心得体会
2016/01/06 职场文书
quickjs 封装 JavaScript 沙箱详情
2021/11/02 Javascript