python 字符串格式化的示例


Posted in Python onSeptember 21, 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.'

参考资料

Python 3's f-Strings: An Improved String Formatting Syntax (Guide)

以上就是python 字符串格式化的示例的详细内容,更多关于python 字符串格式化的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
用Python编写生成树状结构的文件目录的脚本的教程
May 04 Python
详解详解Python中writelines()方法的使用
May 25 Python
Python函数式编程指南(三):迭代器详解
Jun 24 Python
python 添加用户设置密码并发邮件给root用户
Jul 25 Python
浅谈django中的认证与登录
Oct 31 Python
简单谈谈Python中的闭包
Nov 30 Python
Python实现登录接口的示例代码
Jul 21 Python
Python内置函数delattr的具体用法
Nov 23 Python
Python实现的个人所得税计算器示例
Jun 01 Python
记录模型训练时loss值的变化情况
Jun 16 Python
TensorFlow的环境配置与安装方法
Feb 20 Python
python控制台打印log输出重复的解决方法
May 14 Python
基于python判断字符串括号是否闭合{}[]()
Sep 21 #Python
属性与 @property 方法让你的python更高效
Sep 21 #Python
Python如何在bool函数中取值
Sep 21 #Python
python 密码学示例——凯撒密码的实现
Sep 21 #Python
python 密码学示例——理解哈希(Hash)算法
Sep 21 #Python
python中的垃圾回收(GC)机制
Sep 21 #Python
如何在Python3中使用telnetlib模块连接网络设备
Sep 21 #Python
You might like
无数据库的详细域名查询程序PHP版(1)
2006/10/09 PHP
php microtime获取浮点的时间戳
2010/02/21 PHP
AMFPHP php远程调用(RPC, Remote Procedure Call)工具 快速入门教程
2010/05/10 PHP
PHP HTTP 认证实例详解
2016/11/03 PHP
jquery不会自动回收xmlHttpRequest对象 导致了内存溢出
2012/06/18 Javascript
js实现拉伸拖动iframe的具体代码
2013/08/03 Javascript
判断js对象是否拥有某一个属性的js代码
2013/08/16 Javascript
实测jquery data()如何存值
2013/08/18 Javascript
jquery实现适用于门户站的导航下拉菜单效果代码
2015/08/24 Javascript
复杂的javascript窗口分帧解析
2016/02/19 Javascript
jQuery根据ID、CLASS、等获取对象的实例
2016/12/04 Javascript
jQuery图片轮播功能实例代码
2017/01/29 Javascript
详解React Native网络请求fetch简单封装
2017/08/10 Javascript
你可能不知道的JSON.stringify()详解
2017/08/17 Javascript
vue-cli中的babel配置文件.babelrc实例详解
2018/02/22 Javascript
Electron autoUpdater实现Windows安装包自动更新的方法
2018/12/24 Javascript
生成无限制的微信小程序码的示例代码
2019/09/20 Javascript
ElementUI Tree 树形控件的使用并给节点添加图标
2020/02/27 Javascript
使用python BeautifulSoup库抓取58手机维修信息
2013/11/21 Python
Python修改MP3文件的方法
2015/06/15 Python
浅谈python中截取字符函数strip,lstrip,rstrip
2015/07/17 Python
python实现textrank关键词提取
2018/06/22 Python
Python基于递归算法求最小公倍数和最大公约数示例
2018/07/27 Python
用python生成1000个txt文件的方法
2018/10/25 Python
python面向对象法实现图书管理系统
2019/04/19 Python
使用sklearn对多分类的每个类别进行指标评价操作
2020/06/11 Python
python主要用于哪些方向
2020/07/05 Python
python中random模块详解
2021/03/01 Python
柏林通行证:Berlin Pass
2018/04/11 全球购物
迪卡侬印尼体育用品商店:Decathlon印尼
2020/03/11 全球购物
PHP面试题大全
2015/10/16 面试题
师德建设实施方案
2014/03/21 职场文书
歌颂祖国的演讲稿
2014/05/04 职场文书
2015年爱国卫生月活动总结
2015/03/26 职场文书
荒岛余生观后感
2015/06/09 职场文书
2016应届毕业生实习心得体会
2015/10/09 职场文书