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 相关文章推荐
如何搜索查找并解决Django相关的问题
Jun 30 Python
Python解释执行原理分析
Aug 22 Python
零基础写python爬虫之抓取百度贴吧代码分享
Nov 06 Python
python通过配置文件共享全局变量的实例
Jan 11 Python
django 微信网页授权认证api的步骤详解
Jul 30 Python
python实现几种归一化方法(Normalization Method)
Jul 31 Python
python自动化工具之pywinauto实例详解
Aug 26 Python
Python遍历字典方式就实例详解
Dec 28 Python
Ubuntu16.04安装python3.6.5步骤详解
Jan 10 Python
Python对称的二叉树多种思路实现方法
Feb 28 Python
基于Python实现下载网易音乐代码实例
Aug 10 Python
python 输入字符串生成所有有效的IP地址(LeetCode 93号题)
Oct 15 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 Session_Regenerate_ID函数双释放内存破坏漏洞
2011/01/27 PHP
php摘要生成函数(无乱码)
2012/02/04 PHP
PHP同时连接多个mysql数据库示例代码
2014/03/17 PHP
如何在Laravel5.8中正确地应用Repository设计模式
2019/11/26 PHP
PHP的图像处理实例小结【文字水印、图片水印、压缩图像等】
2019/12/20 PHP
使javascript也能包含文件
2006/10/26 Javascript
“不能执行已释放的Script代码”错误的原因及解决办法
2007/09/09 Javascript
JavaScript匿名函数之模仿块级作用域
2015/12/12 Javascript
基于BootStrap的图片轮播效果展示实例代码
2016/05/23 Javascript
让DIV的滚动条自动滚动到最底部的3种方法(推荐)
2016/09/24 Javascript
js选项卡的制作方法
2017/01/23 Javascript
原生js FileReader对象实现图片上传本地预览效果
2020/03/27 Javascript
微信小程序实现带缩略图轮播效果
2018/11/04 Javascript
详解webpack+ES6+Sass搭建多页面应用
2018/11/05 Javascript
React 使用Hooks简化受控组件的状态绑定
2019/03/18 Javascript
ES6 Object.assign()的用法及其使用
2020/01/18 Javascript
JavaScript原型继承和原型链原理详解
2020/02/04 Javascript
jquery实现拖拽小方块效果
2020/12/10 jQuery
wxpython 最小化到托盘与欢迎图片的实现方法
2014/06/09 Python
python实现自动登录人人网并访问最近来访者实例
2014/09/26 Python
浅谈用Python实现一个大数据搜索引擎
2017/11/28 Python
快速解决安装python没有scripts文件夹的问题
2018/04/03 Python
Python 3.7新功能之dataclass装饰器详解
2018/04/21 Python
python3中函数参数的四种简单用法
2018/07/09 Python
python+splinter实现12306网站刷票并自动购票流程
2018/09/25 Python
python3+selenium实现126邮箱登陆并发送邮件功能
2019/01/23 Python
Python+OpenCV图片局部区域像素值处理改进版详解
2019/01/23 Python
Python基于pandas绘制散点图矩阵代码实例
2020/06/04 Python
自荐信要包含哪些内容
2013/11/06 职场文书
高一自我鉴定
2013/12/17 职场文书
公司收款委托书范本
2014/09/20 职场文书
乡镇2014法制宣传日活动总结
2014/11/01 职场文书
2019公司借款合同范本2篇!
2019/07/24 职场文书
导游词之江南园林狮子林
2019/09/16 职场文书
JS新手入门数组处理的实用方法汇总
2021/04/07 Javascript
Python编写nmap扫描工具
2021/07/21 Python