Python format() 函数

pythonserver side programmingprogramming更新于 2025/7/31 6:36:17

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

相关文章


有用资源