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类定义的讲解
Nov 01 Python
github配置使用指南
Nov 18 Python
Python基于动态规划算法计算单词距离
Jul 25 Python
Python中扩展包的安装方法详解
Jun 14 Python
django缓存配置的几种方法详解
Jul 16 Python
Python字典循环添加一键多值的用法实例
Jan 20 Python
Python3.6.x中内置函数总结及讲解
Feb 22 Python
python3 常见解密加密算法实例分析【base64、MD5等】
Dec 19 Python
pycharm 更改创建文件默认路径的操作
Feb 15 Python
TensorFlow的reshape操作 tf.reshape的实现
Apr 19 Python
Python+Kepler.gl轻松制作酷炫路径动画的实现示例
Jun 02 Python
总结Pyinstaller的坑及终极解决方法(小结)
Sep 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和mysql的简单的dao类实现crud操作功能
2014/01/27 PHP
一个PHP的ZIP压缩类分享
2014/05/04 PHP
PHP进阶学习之依赖注入与Ioc容器详解
2019/06/19 PHP
PHP Trait功能与用法实例分析
2020/06/03 PHP
关于JavaScript定义类和对象的几种方式
2010/11/09 Javascript
网页运行时提示对象不支持abigimage属性或方法
2014/08/10 Javascript
JS实现的另类手风琴效果网页内容切换代码
2015/09/08 Javascript
AngularJS 实现按需异步加载实例代码
2015/10/18 Javascript
JavaScript模拟数组合并concat
2016/03/06 Javascript
jQuery 判断是否包含在数组中Array[]的方法
2016/08/03 Javascript
js倒计时简单实现代码
2016/08/11 Javascript
bootstrap表单示例代码分享
2017/05/18 Javascript
解决webpack -p压缩打包react报语法错误的方法
2017/07/03 Javascript
JS正则表达式完美实现身份证校验功能
2017/10/18 Javascript
详解使用create-react-app添加css modules、sasss和antd
2018/07/31 Javascript
JavaScript 浏览器对象模型BOM原理与常见用法实例分析
2019/12/16 Javascript
Vue-router 报错NavigationDuplicated的解决方法
2020/03/31 Javascript
[01:20]DOTA2 齐天大圣至宝动态展示
2016/12/13 DOTA
python创建和使用字典实例详解
2013/11/01 Python
python使用turtle库绘制时钟
2020/03/25 Python
python实现LRU热点缓存及原理
2019/10/29 Python
python getopt模块使用实例解析
2019/12/18 Python
SpringBoot首页设置解析(推荐)
2021/02/11 Python
任意一块网页内容实现“活”的背景(目前火狐浏览器专有)
2014/05/07 HTML / CSS
【HTML5】3D模型--百行代码实现旋转立体魔方实例
2016/12/16 HTML / CSS
体育专业个人的求职信范文
2013/09/21 职场文书
中英双版中文教师求职信
2013/10/27 职场文书
应届优秀本科大学毕业生自我鉴定
2014/01/21 职场文书
初三化学教学反思
2014/01/23 职场文书
2014小学植树节活动总结
2014/03/10 职场文书
2015年学校心理健康教育工作总结
2015/05/11 职场文书
项目备案申请报告
2015/05/15 职场文书
通讯稿格式及范文
2015/07/22 职场文书
python基础学习之递归函数知识总结
2021/05/26 Python
mybatis中sql语句CDATA标签的用法说明
2021/06/30 Java/Android
Vue3.0中Ref与Reactive的区别示例详析
2021/07/07 Vue.js