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之集成开发环境(IDE)
Sep 12 Python
举例讲解Python程序与系统shell交互的方式
Apr 09 Python
Python实现的飞速中文网小说下载脚本
Apr 23 Python
Python批量按比例缩小图片脚本分享
May 21 Python
Python生成密码库功能示例
May 23 Python
Python中使用Counter进行字典创建以及key数量统计的方法
Jul 06 Python
Python Learning 列表的更多操作及示例代码
Aug 22 Python
Django MEDIA的配置及用法详解
Jul 25 Python
Django在pycharm下修改默认启动端口的方法
Jul 26 Python
Django外键(ForeignKey)操作以及related_name的作用详解
Jul 29 Python
Python坐标线性插值应用实现
Nov 13 Python
Python+opencv+pyaudio实现带声音屏幕录制
Dec 23 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
Terran历史背景
2020/03/14 星际争霸
一文看懂PHP进程管理器php-fpm
2020/06/01 PHP
javascript中关于执行环境的杂谈
2011/08/14 Javascript
Javascript浮点数乘积运算出现多位小数的解决方法
2014/02/17 Javascript
轻松学习jQuery插件EasyUI EasyUI创建树形网络(1)
2015/11/30 Javascript
跨域资源共享 CORS 详解
2016/04/26 Javascript
Vue.js每天必学之组件与组件间的通信
2016/09/08 Javascript
学习Node.js模块机制
2016/10/17 Javascript
jQuery实现点击下拉框中的值累加到文本框中的方法示例
2017/10/28 jQuery
vue-router相关基础知识及工作原理
2018/03/16 Javascript
jQuery实现的点击标题文字切换字体效果示例【测试可用】
2018/04/26 jQuery
jQuery实现简单的Ajax调用功能示例
2019/02/15 jQuery
简述vue-cli中chainWebpack的使用方法
2019/07/30 Javascript
微信小程序HTTP请求从0到1封装
2019/09/09 Javascript
解决vue组件中click事件失效的问题
2019/11/09 Javascript
Vue自定义render统一项目组弹框功能
2020/06/07 Javascript
[03:08]Ti4观战指南上
2014/07/07 DOTA
[01:13:01]2018DOTA2亚洲邀请赛 4.4 淘汰赛 TNC vs VG 第三场
2018/04/05 DOTA
web.py 十分钟创建简易博客实现代码
2016/04/22 Python
pygame游戏之旅 调用按钮实现游戏开始功能
2018/11/21 Python
pytorch-神经网络拟合曲线实例
2020/01/15 Python
django xadmin中form_layout添加字段显示方式
2020/03/30 Python
Python MOCK SERVER moco模拟接口测试过程解析
2020/04/13 Python
Django Form设置文本框为readonly操作
2020/07/03 Python
Python paramiko使用方法代码汇总
2020/11/20 Python
Clearly澳大利亚:购买眼镜、太阳镜和隐形眼镜
2018/04/26 全球购物
W Hamond官网:始于1979年的钻石专家
2020/07/20 全球购物
英国最大的在线照明商店:Litecraft
2020/08/31 全球购物
宣传策划类求职信范文
2014/01/31 职场文书
护士试用期自我鉴定
2014/02/08 职场文书
经理助理岗位职责
2014/03/05 职场文书
元宵节晚会主持人串词
2014/03/25 职场文书
《天游峰的扫路人》教学反思
2014/04/25 职场文书
大专生自荐书范文
2014/06/22 职场文书
运动会入场词
2015/07/18 职场文书
go goroutine 怎样进行错误处理
2021/07/16 Golang