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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短