首页 > 编程 > Python > 正文

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

2020-02-23 06:01:54
字体:
来源:转载
供稿:网友

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

基本的操作

所谓格式化方法,就是可以先建立一个输出字符串的模板,然后用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'

对上面的综合一下,稍微啰嗦一点的实验:

代码如下:
>>> 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.'

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表