跟老齐学Python之从格式化表达式到方法


Posted in Python onSeptember 28, 2014

现在我们就格式化方法做一个详细一点的交代。

基本的操作

所谓格式化方法,就是可以先建立一个输出字符串的模板,然后用format来填充模板的内容。

>>> #先做一个字符串模板

>>> template = "My name is {0}. My website is {1}. I am writing {2}."
>>> #用format依次对应模板中的序号内容

>>> template.format("qiwsir","qiwsir.github.io","python")

'My name is qiwsir. My website is qiwsir.github.io. I am writing python.'

当然,上面的操作如果你要这样做,也是可以的:

>>> "My name is {0}. My website is {1}. I am writing {2}.".format("qiwsir","qiwsir.github.io","python")

'My name is qiwsir. My website is qiwsir.github.io. I am writing python.'

这些,跟用%写的表达式没有什么太大的区别。不过看官别着急,一般小孩子都区别不到,长大了才有区别的。慢慢看,慢慢实验。

除了可以按照对应顺序(类似占位符了)填充模板中的位置之外,还能这样,用关键字来指明所应该田中的内容。

>>> template = "My name is {name}. My website is {site}"

>>> template.format(site='qiwsir.github.io', name='qiwsir')

'My name is qiwsir. My website is qiwsir.github.io'

关键词所指定的内容,也不一定非是str,其它的数据类型也可以。此外,关键词和前面的位置编号,还可以混用。比如:

>>> "{number} is in {all}. {0} are my number.".format("seven",number=7,all=[1,2,3,4,5,6,7,8,9,0])

'7 is in [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]. seven are my number.'

是不是开始感觉有点意思了?看输出结果,就知道,经过format方法得到是一个新的str。

序列对象的偏移量

有这样一个要求:在输出中,显示出一个单词的第一个字母和第三个个字母。比如单词python,要告诉看官,第一字母是p,第三个字母是t。

这个问题并不难。实现方法也不少,这里主要是要展示一下偏移量在format中的应用。

>>> template = "First={0[0]}, Third={0[2]}"

>>> template.format(word)

'First=p, Third=t'

list也是序列类型的,其偏移量也可。

>>> word_lst = list(word)

>>> word_lst

['p', 'y', 't', 'h', 'o', 'n']

>>> template

'First={0[0]}, Third={0[2]}'

>>> template.format(word_lst)

'First=p, Third=t'

对上面的综合一下,稍微??乱坏愕氖笛椋?/p>

>>> template = "The word is {0}, Its first is {0[0]}. Another word is {1}, Its second is {1[1]}."

>>> template.format("python","learn")

'The word is python, Its first is p. Another word is learn, Its second is e.'
>>> "{name}\'s first is {name[0]}".format(name="qiwsir")    #指定关键词的值的偏移量

"qiwsir's first is q"

值得注意的是,偏移量在序列类型的数据中,因为可以是负数,即能够从右边开始计数。

>>> word

'python'

>>> word[-1]

'n'

>>> word[-2]

'o'

但是,在模板中,无法使用负数的偏移量。

>>> "First={0[0]}, End={0[-1]}".format(word) #报错

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: string indices must be integers, not str
>>> "First={0[0]}, End={0[5]}".format(word)  #把-1改为5就可以了。

'First=p, End=n'

当然,放到模板外面是完全可行的。这样就好了:

>>> "First={0}, End={1}".format(word[0],word[-1])

'First=p, End=n'

dictionary的键

直接上实验,先观察,再得结论

>>> myinfo

{'website': 'qiwsir.github.io', 'name': 'qiwsir', 'room': 703}

>>> template = "I am {0[name]}"

>>> template.format(myinfo)

'I am qiwsir'

>>> template = "I am {0[name]}. My QQ is {qq}"

>>> template.format(myinfo,qq="26066913")

'I am qiwsir. My QQ is 26066913'

位置后面跟键,就能得到format的参数中字典的键对应的值。太罗嗦了吧,看例子就明白了。出了根据位置得到,还能够根据关键词得到:

>>> myinfo

{'website': 'qiwsir.github.io', 'name': 'qiwsir', 'room': 703}

>>> "my website is {info[website]}, and I like {0}".format("python",info=myinfo)    #关键词info引用的是一个字典

'my website is qiwsir.github.io, and I like python'

模板中添加属性

看标题不懂在说什么。那就看实验吧。

>>> import math

>>> "PI is {PI.pi}".format(PI=math)

'PI is 3.14159265359'

这是用关键词,下面换个稍微复杂点,用位置的。

>>> import sys,math

>>> 'PI is {0.pi}. My lptop runs {1.platform}'.format(math,sys)

'PI is 3.14159265359. My lptop runs linux2'

看官理解了吧。

其它进制

在这个世界上的数学领域,除了有我们常常用到的十进制、十二进制(几点了,这是你我常用到的,钟表面就是12进制)、六十进制(这个你也熟悉的)外,还有别的进制,比如二进制、八进制、十六进制等等。此处不谈进制问题,有兴趣详细了解,请各自google。不过,进制的确在计算机上很重要的。因为机器在最底层是用二进制的。

这里只是说明一下输出时候的进制问题。

>>> "{0:X}, {1:o}, {2:b}".format(255,255,255)
'FF, 377, 11111111'
X:十六进制,Hex
o:八进制,octal
b:二进制,binary
顺便补充,对于数的格式化方法输出和格式化表达式一样,就不赘述了。

在格式化方法中,还能够指定字符宽度,左右对齐等简单排版格式,不过,在我的经验中,这些似乎用的不怎么多。如果看官需要,可以google或者到官方文档看看即可。

关于格式化表达式和格式化方法,有的人进行了不少比较,有的人说用这个,有的人倾向用那个。我的建议是,你用哪个顺手就用哪个。切忌门派之见呀。不过,有人传说格式化表达式可能在将来某个版本中废除。那是将来的事情,将来再说好了。现在,你就捡着顺手的用吧。

Python 相关文章推荐
python中的一些类型转换函数小结
Feb 10 Python
python 实时遍历日志文件
Apr 12 Python
Python中格式化format()方法详解
Apr 01 Python
Python中的错误和异常处理简单操作示例【try-except用法】
Jul 25 Python
Python + selenium自动化环境搭建的完整步骤
May 19 Python
浅析python3中的os.path.dirname(__file__)的使用
Aug 30 Python
使用python批量读取word文档并整理关键信息到excel表格的实例
Nov 07 Python
python提取具有某种特定字符串的行数据方法
Dec 11 Python
Python操作远程服务器 paramiko模块详细介绍
Aug 07 Python
Python程序慢的重要原因
Sep 04 Python
python scrapy简单模拟登录的代码分析
Jul 21 Python
python中的sys模块和os模块
Mar 20 Python
跟老齐学Python之print详解
Sep 28 #Python
跟老齐学Python之正规地说一句话
Sep 28 #Python
跟老齐学Python之玩转字符串(2)更新篇
Sep 28 #Python
跟老齐学Python之不要红头文件(2)
Sep 28 #Python
跟老齐学Python之不要红头文件(1)
Sep 28 #Python
python自动化测试之连接几组测试包实例
Sep 28 #Python
python自动化测试之从命令行运行测试用例with verbosity
Sep 28 #Python
You might like
Content-type 的说明
2006/10/09 PHP
无法载入 mcrypt 扩展,请检查 PHP 配置终极解决方案
2011/07/18 PHP
php中删除字符串中最先出现某个字符的实现代码
2013/02/03 PHP
smarty模板中使用get、post、request、cookies、session变量的方法
2014/04/24 PHP
PHP实现自动登入google play下载app report的方法
2014/09/23 PHP
php使用PDO方法详解
2014/12/27 PHP
WordPress中访客登陆实现邮件提醒的PHP脚本实例分享
2015/12/14 PHP
PHP自定义错误用法示例
2016/09/28 PHP
一个可以兼容IE FF的加为首页与加入收藏实现代码
2009/11/02 Javascript
JavaScript Cookie的读取和写入函数
2009/12/08 Javascript
javascript 全等号运算符使用说明
2010/05/31 Javascript
jquery弹出框的用法示例(一)
2013/08/26 Javascript
Knockout text绑定DOM的使用方法
2013/11/15 Javascript
JavaScript操作select元素和option的实例代码
2016/01/29 Javascript
nodejs入门教程六:express模块用法示例
2017/04/24 NodeJs
js实现加载页面就自动触发超链接的示例
2017/08/31 Javascript
jQuery实现的文字逐行向上间歇滚动效果示例
2017/09/06 jQuery
mint-ui 时间插件使用及获取选择值的方法
2018/02/09 Javascript
详解VUE里子组件如何获取父组件动态变化的值
2018/12/26 Javascript
微信小程序获取公众号文章列表及显示文章的示例代码
2020/03/10 Javascript
详解vue-flickity的fullScreen功能实现
2020/04/07 Javascript
解决python3 安装完Pycurl在import pycurl时报错的问题
2018/10/15 Python
通过cmd进入python的实例操作
2019/06/26 Python
Python+OpenCv制作证件图片生成器的操作方法
2019/08/21 Python
PyCharm搭建Spark开发环境的实现步骤
2019/09/05 Python
python使用docx模块读写docx文件的方法与docx模块常用方法详解
2020/02/17 Python
Python接收手机短信的代码整理
2020/08/02 Python
pytorch简介
2020/11/11 Python
The Kooples美国官方网站:为情侣提供的法国当代时尚品牌
2019/01/03 全球购物
副厂长岗位职责
2014/02/02 职场文书
酒店周年庆活动方案
2014/08/21 职场文书
大学生自我评价200字(4篇)
2014/09/17 职场文书
企业三严三实学习心得体会
2014/10/13 职场文书
后勤个人工作总结
2015/02/28 职场文书
2019年大学生学年自我鉴定!
2019/03/25 职场文书
python入门之算法学习
2021/04/22 Python