Python format()函数
该format()方法格式化一些指定的值并将其插入到字符串的占位符中。占位符由{}表示。在本文中,我们将介绍格式函数的各种使用方式。
单format()
在此示例中,将给定范围内的数字替换为带有固定字符串的占位符。
示例
for i in range(19,25):
print("There are {} boxes!".format(i))输出结果
运行上面的代码给我们以下结果-
There are 19 boxes! There are 20 boxes! There are 21 boxes! There are 22 boxes! There are 23 boxes! There are 24 boxes!
多format()
在此示例中,我们使用多个参数,因此可以与多个占位符一起使用。
示例
i=1
months={'Jan','Feb','Mar'}
for m in months:
print("Month no {} is {}".format(i,m))
i=i+1输出结果
运行上面的代码给我们以下结果-
Month no 1 is Jan Month no 2 is Mar Month no 3 is Feb
使用位置索引
特定的占位符可以用格式字符串中参数的特定位置填充。
示例
print("This week I'm workigm on {1},{2} and {4}".format('Mon','Tue','Wed','Thu','Fri'))输出结果
运行上面的代码给我们以下结果-
This week I'm workigm on Tue,Wed and Fri
使用关键字
我们还可以使用关键字以及可以放在容器中的符号。
示例
print("The 3{r}, 4{t} and 5{t} ranks are winners".format(r='rd',t='th'))输出结果
运行上面的代码给我们以下结果-
The 3rd, 4th and 5th ranks are winners
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便