Python中字符串格式化str.format的详细介绍


Posted in Python onFebruary 17, 2017

前言

Python 在 2.6 版本中新加了一个字符串格式化方法: str.format() 。它的基本语法是通过 {} 和 : 来代替以前的 %.。

格式化时的占位符语法:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"

“映射”规则

通过位置

str.format() 可以接受不限个参数,位置可以不按顺序:

>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'

通过关键字参数

使用关键参数时字符串中需要提供参数名:

>>> "I am {name}, age is {age}".format(name="huoty", age=18)
'I am huoty, age is 18'
>>> user = {"name": "huoty", "age": 18}
>>> "I am {name}, age is {age}".format(**user)
'I am huoty, age is 18'

通过对象属性

str.format() 可以直接读取用户属性:

>>> class User(object):
...  def __init__(self, name, age):
...   self.name = name
...   self.age = age
...   
...  def __str__(self):
...   return "{self.name}({self.age})".format(self=self)
...  
...  def __repr__(self):
...   return self.__str__()
...  
...
>>> user = User("huoty", 18)
>>> user
huoty(18)
>>> "I am {user.name}, age is {user.age}".format(user=user)
'I am huoty, age is 18'

通过下标

在需要格式化的字符串内部可以通过下标来访问元素:

>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8]
>>> "I am {0[0]}, age is {1[2]}".format(names, ages)
'I am huoty, age is 8'
>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}
>>> "I am {names[0]}, age is {ages[0]}".format(**users)

指定转化

可以指定字符串的转化类型:

conversion ::= "r" | "s" | "a"

其中 "!r" 对应 repr(); "!s" 对应 str(); "!a" 对应 ascii()。 示例:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

格式限定符

填充与对齐

填充常跟对齐一起使用。^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

>>> "{:>8}".format("181716")
' 181716'
>>> "{:0>8}".format("181716")
'00181716'
>>> "{:->8}".format("181716")
'--181716'
>>> "{:-<8}".format("181716")
'181716--'
>>> "{:-^8}".format("181716")
'-181716-'
>>> "{:-<25}>".format("Here ")
'Here -------------------->'

浮点精度

用 f 表示浮点类型,并可以在其前边加上精度控制:

>>> "[ {:.2f} ]".format(321.33345)
'[ 321.33 ]'
>>> "[ {:.1f} ]".format(321.33345)
'[ 321.3 ]'
>>> "[ {:.4f} ]".format(321.33345)
'[ 321.3335 ]'
>>> "[ {:.4f} ]".format(321)
'[ 321.0000 ]'

还可以为浮点数指定符号,+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格,在幅负数前加 -;- 与什么都不加({:f})时一致:

>>> '{:+f}; {:+f}'.format(3.141592657, -3.141592657)
'+3.141593; -3.141593'
>>> '{: f}; {: f}'.format(3.141592657, -3.141592657)
' 3.141593; -3.141593'
>>> '{:f}; {:f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:-f}; {:-f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:+.4f}; {:+.4f}'.format(3.141592657, -3.141592657)
'+3.1416; -3.1416'

指定进制

>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(18)
'int: 18; hex: 12; oct: 22; bin: 10010'
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(18)
'int: 18; hex: 0x12; oct: 0o22; bin: 0b10010'

千位分隔符

可以使用 "," 来作为千位分隔符:

>>> '{:,}'.format(1234567890)
'1,234,567,890'

百分数显示

>>> "progress: {:.2%}".format(19.88/22)
'progress: 90.36%'

事实上,format 还支持更多的类型符号:

type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

其他技巧

占位符嵌套

某些时候占位符嵌套还是很有用的:

>>> '{0:{fill}{align}16}'.format("hello", fill='*', align='^')
'*****hello******'
>>>
>>> for num in range(5,12):
...  for base in "dXob":
...   print("{0:{width}{base}}".format(num, base=base, width=5), end=' ')
...  print()
...  
...
 5  5  5 101
 6  6  6 110
 7  7  7 111
 8  8 10 1000
 9  9 11 1001
 10  A 12 1010
 11  B 13 1011

作为函数使用

可以先不指定格式化参数,而是在不要的地方作为函数来调用:

>>> email_f = "Your email address was {email}".format
>>> print(email_f(email="suodhuoty@gmail.com"))
Your email address was sudohuoty@gmail.com

转义大括号

当在字符串中需要使用大括号时可以用大括号转义:

>>> " The {} set is often represented as { {0} } ".format("empty")
' The empty set is often represented as {0} '

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Python 相关文章推荐
Python实现比较两个列表(list)范围
Jun 12 Python
Python使用poplib模块和smtplib模块收发电子邮件的教程
Jul 02 Python
Python 编码Basic Auth使用方法简单实例
May 25 Python
python使用fork实现守护进程的方法
Nov 16 Python
人生苦短我用python python如何快速入门?
Mar 12 Python
python 把文件中的每一行以数组的元素放入数组中的方法
Apr 29 Python
用python3 urllib破解有道翻译反爬虫机制详解
Aug 14 Python
Python3简单爬虫抓取网页图片代码实例
Aug 26 Python
python使用PIL和matplotlib获取图片像素点并合并解析
Sep 10 Python
opencv3/C++ 平面对象识别&amp;透视变换方式
Dec 11 Python
python中的逆序遍历实例
Dec 25 Python
Python3操作读写CSV文件使用包过程解析
Apr 10 Python
Python爬虫:通过关键字爬取百度图片
Feb 17 #Python
Python 遍历列表里面序号和值的方法(三种)
Feb 17 #Python
浅谈python中的实例方法、类方法和静态方法
Feb 17 #Python
Python之日期与时间处理模块(date和datetime)
Feb 16 #Python
python字符串中的单双引
Feb 16 #Python
使用PyV8在Python爬虫中执行js代码
Feb 16 #Python
Python错误提示:[Errno 24] Too many open files的分析与解决
Feb 16 #Python
You might like
用PHP读取flv文件的播放时间长度
2009/09/03 PHP
php 智能404跳转代码,适合换域名没改变目录的网站
2010/06/04 PHP
php实现Linux服务器木马排查及加固功能
2014/12/29 PHP
PHP使用PDO操作sqlite数据库应用案例
2019/03/07 PHP
greybox——不开新窗口看新的网页
2007/02/20 Javascript
javascript 动态调整图片尺寸实现代码
2009/12/28 Javascript
div当滚动到页面顶部的时候固定在顶部实例代码
2013/05/27 Javascript
jqgrid 编辑添加功能详细解析
2013/11/08 Javascript
浅析JQuery UI Dialog的样式设置问题
2013/12/18 Javascript
判断复选框是否被选中的两种方法
2014/06/04 Javascript
Javascript学习笔记之 函数篇(二) : this 的工作机制
2014/06/24 Javascript
JavaScript每天必学之数组和对象部分
2016/09/17 Javascript
使用koa2创建web项目的方法步骤
2019/03/12 Javascript
使用JS判断页面是首次被加载还是刷新
2019/05/26 Javascript
详解Vue 如何监听Array的变化
2019/06/06 Javascript
微信小程序实现通讯录列表展开收起
2020/11/18 Javascript
[03:55]显微镜下的DOTA2特别篇——430灰烬之灵神级操作
2014/06/24 DOTA
[01:32]DOTA2 2015国际邀请赛中国区预选赛第四日战报
2015/05/29 DOTA
[02:23]2016国际邀请赛中国区预选赛wings晋级之路
2016/06/29 DOTA
跟老齐学Python之永远强大的函数
2014/09/14 Python
Python中 Lambda表达式全面解析
2016/11/28 Python
Python实现模拟分割大文件及多线程处理的方法
2017/10/10 Python
解决新版Pycharm中Matplotlib图像不在弹出独立的显示窗口问题
2019/01/15 Python
Python利用pandas处理Excel数据的应用详解
2019/06/18 Python
Python3和PyCharm安装与环境配置【图文教程】
2020/02/14 Python
初中生学习的自我评价
2013/11/14 职场文书
酒吧员工的岗位职责
2013/11/26 职场文书
《小儿垂钓》教学反思
2014/02/23 职场文书
本科毕业生求职信
2014/06/15 职场文书
医学求职自荐信
2014/06/21 职场文书
第一批党的群众路线教育实践活动总结报告
2014/07/03 职场文书
2014年审计工作总结
2014/11/17 职场文书
2014年财务经理工作总结
2014/12/08 职场文书
听证会主持词
2015/07/03 职场文书
教师年度考核自我评鉴
2015/08/11 职场文书
Node-Red实现MySQL数据库连接的方法
2021/08/07 MySQL