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 sort、sorted高级排序技巧
Nov 21 Python
Python实现建立SSH连接的方法
Jun 03 Python
星球大战与Python之间的那些事
Jan 07 Python
python用pickle模块实现“增删改查”的简易功能
Jun 07 Python
python Pandas 读取txt表格的实例
Apr 29 Python
Python爬虫爬取新浪微博内容示例【基于代理IP】
Aug 03 Python
Python3.6简单的操作Mysql数据库的三个实例
Oct 17 Python
使用selenium和pyquery爬取京东商品列表过程解析
Aug 15 Python
python 如何快速复制序列
Sep 07 Python
python爬虫利器之requests库的用法(超全面的爬取网页案例)
Dec 17 Python
python 三边测量定位的实现代码
Apr 22 Python
k-means & DBSCAN 总结
Apr 27 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
如何过滤高亮显示非法字符
2006/10/09 PHP
PHP实现Javascript中的escape及unescape函数代码分享
2015/02/10 PHP
PHP的mysqli_sqlstate()函数讲解
2019/01/23 PHP
javascript英文日期(有时间)选择器
2007/05/02 Javascript
jquery.validate使用攻略 第二部
2010/07/01 Javascript
Firefox中使用outerHTML的2种解决方法
2014/06/07 Javascript
对之前写的jquery分页做下升级
2014/06/19 Javascript
JS实现CheckBox复选框全选全不选功能
2015/05/06 Javascript
简介JavaScript中substring()方法的使用
2015/06/06 Javascript
ichart.js绘制虚线、平均分虚线效果的实现代码
2016/05/05 Javascript
Vuejs第六篇之Vuejs与form元素实例解析
2016/09/05 Javascript
javascript代码调试之console.log 用法图文详解
2016/09/30 Javascript
Mui使用jquery并且使用点击跳转新窗口的实例
2017/08/19 jQuery
使用webpack打包后的vue项目如何正确运行(express)
2018/10/26 Javascript
基于JavaScript实现单例模式
2019/10/30 Javascript
vue实现输入一位数字转汉字功能
2019/12/13 Javascript
[01:28:56]2014 DOTA2华西杯精英邀请赛 5 24 CIS VS DK
2014/05/26 DOTA
python实现查找两个字符串中相同字符并输出的方法
2015/07/11 Python
Python保存MongoDB上的文件到本地的方法
2016/03/16 Python
Python的爬虫程序编写框架Scrapy入门学习教程
2016/07/02 Python
对python numpy数组中冒号的使用方法详解
2018/04/17 Python
Windows系统Python直接调用C++ DLL的方法
2019/08/01 Python
Win10 安装PyCharm2019.1.1(图文教程)
2019/09/29 Python
python logging 日志的级别调整方式
2020/02/21 Python
详解matplotlib中pyplot和面向对象两种绘图模式之间的关系
2021/01/22 Python
Python爬虫入门教程02之笔趣阁小说爬取
2021/01/24 Python
python解决OpenCV在读取显示图片的时候闪退的问题
2021/02/23 Python
Mamaearth官方网站:印度母婴护理产品公司
2019/10/06 全球购物
计算机专业个人求职自荐信
2013/09/21 职场文书
药学职务聘任书
2014/03/29 职场文书
什么是就业协议书
2014/04/17 职场文书
毕业生评语大全
2015/01/04 职场文书
信息技术远程培训心得体会
2016/01/09 职场文书
古诗之感恩老师
2019/10/24 职场文书
【D4DJ】美少女DJ企划 动画将于明年冬季开播第2季
2022/04/11 日漫
Java版 简易五子棋小游戏
2022/05/04 Java/Android