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中的jquery PyQuery库使用小结
May 13 Python
python快速查找算法应用实例
Sep 26 Python
在Gnumeric下使用Python脚本操作表格的教程
Apr 14 Python
Python查找函数f(x)=0根的解决方法
May 07 Python
详解用python计算阶乘的几种方法
Aug 14 Python
python第三方库学习笔记
Feb 07 Python
Macbook安装Python最新版本、GUI开发环境、图像处理、视频处理环境详解
Feb 17 Python
如何在Python 游戏中模拟引力
Mar 27 Python
PyCharm+Pipenv虚拟环境开发和依赖管理的教程详解
Apr 16 Python
Python通过kerberos安全认证操作kafka方式
Jun 06 Python
Python就将所有的英文单词首字母变成大写
Feb 12 Python
Python Pandas pandas.read_sql函数实例用法
Jun 21 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 Rename 更改文件、文件夹名称
2011/05/24 PHP
php获取post中的json数据的实现方法
2011/06/08 PHP
PHP多个版本的分析解释
2011/07/21 PHP
php将session放入memcached的设置方法
2014/02/14 PHP
php实现encode64编码类实例
2015/03/24 PHP
Symfony2实现从数据库获取数据的方法小结
2016/03/18 PHP
PHP封装的mysqli数据库操作类示例
2019/02/16 PHP
PHP 图片处理
2020/09/16 PHP
常规表格多表头查询示例
2014/02/21 Javascript
Jquery的each里用return true或false代替break或continue
2014/05/21 Javascript
使用nodejs、Python写的一个简易HTTP静态文件服务器
2014/07/18 NodeJs
javascript实现类似超链接的效果
2014/12/26 Javascript
JS实现自动定时切换的简洁网页选项卡效果
2015/10/13 Javascript
基于JS实现bookstore静态页面的实例代码
2017/02/22 Javascript
JavaScript事件委托原理与用法实例分析
2018/06/07 Javascript
深入了解Vue.js 混入(mixins)
2020/07/23 Javascript
如何使用JavaScript实现无缝滚动自动播放轮播图效果
2020/08/20 Javascript
Python3安装Pymongo详细步骤
2017/05/26 Python
简单谈谈Python的pycurl模块
2018/04/07 Python
对Python 文件夹遍历和文件查找的实例讲解
2018/04/26 Python
Python基础知识点 初识Python.md
2019/05/14 Python
Python 爬虫实现增加播客访问量的方法实现
2019/10/31 Python
将数据集制作成VOC数据集格式的实例
2020/02/17 Python
详解Python 实现 ZeroMQ 的三种基本工作模式
2020/03/24 Python
详解KMP算法以及python如何实现
2020/09/18 Python
尤为Wconcept中国官网:韩国设计师品牌服饰
2019/01/10 全球购物
德国户外商店:eXXpozed
2020/07/25 全球购物
会计员岗位职责
2014/03/15 职场文书
学术诚信承诺书
2014/05/26 职场文书
公务员群众路线专题民主生活会发言材料
2014/09/17 职场文书
干部职工纪律作风整改措施思想汇报
2014/10/11 职场文书
人才市场接收函
2015/01/30 职场文书
明星邀请函
2015/02/02 职场文书
八年级作文之感悟亲情
2019/11/20 职场文书
Python基于Tkinter开发一个爬取B站直播弹幕的工具
2021/05/06 Python
Python中生成随机数据安全性、多功能性、用途和速度方面进行比较
2022/04/14 Python