Python format() 函数根据格式化程序以指定格式返回给定值。
format() 是内置函数之一,可用于各种目的,例如创建格式良好的字符串、特定于类型的格式、格式化数字、字符串对齐和填充等。
语法
以下是 Python format() 函数的语法 -
format(value, formatSpec = '')
参数
Python format() 函数接受以下参数 -
返回值
Python format() 函数根据指定格式返回所传递值的格式化表示形式。
format() 函数示例
练习以下示例来理解 Python 中 format() 函数的使用:
示例:使用 format() 函数
以下示例演示如何使用 Python format() 函数将给定数字格式化为特定形式。在这里,此功能应用于多个数字以将它们格式化为不同的形式。
numOne = 5100200300
formattedNum = format(numOne, ",")
print("Formatting the number using separator:", formattedNum)
numTwo = 12.756
formattedNum = format(numTwo, ".2%")
print("Rounding the given number:",formattedNum)
numThree = 500300200
formattedNum = format(numThree, "e")
print("Converting number into exponential notation:", formattedNum)
numFour = 541.58786
formattedNum = format(numFour, ".2f")
print("Formatting number to two decimal places:", formattedNum)
当我们运行上述程序时,它会产生以下结果——
Formatting the number using separator: 5,100,200,300
Rounding the given number: 1275.60%
Converting number into exponential notation: 5.003002e+08
Formatting number to two decimal places: 541.59
Rounding the given number: 1275.60%
Converting number into exponential notation: 5.003002e+08
Formatting number to two decimal places: 541.59
示例:将 Decimal 转换为二进制、Octal 和 Hexadecimal 格式
Python format() 函数可用于将给定数字转换为其相应的二进制、八进制和十六进制表示形式,如以下示例所示。
nums = 124
binaryNum = format(nums, "b")
octalNum = format(nums, "o")
hexNum = format(nums, "x")
print("Converting number into Binary:", binaryNum)
print("Converting number into Octal:", octalNum)
print("Converting number into Hexadecimal:", hexNum)
当我们运行上述程序时,它会产生以下结果——
Converting number into Binary: 1111100
Converting number into Octal: 174
Converting number into Hexadecimal: 7c
Converting number into Octal: 174
Converting number into Hexadecimal: 7c
示例:覆盖 __format__ 类方法
通过覆盖类中的 “__format__” 方法,我们可以自定义该类的对象的格式。下面的代码演示了相同的操作。
import datetime
class DefDate:
def __init__(self, year, month, day):
self.date = datetime.date(year, month, day)
def __format__(self, formatSpec):
return self.date.strftime(formatSpec)
formattedDate = DefDate(2024, 4, 17)
print("Date after formatting:")
print(format(formattedDate, "%B %d, %Y"))
上述代码的输出如下 -
Date after formatting:
April 17, 2024
April 17, 2024