Tutorial Study Image

Python format()

format() 方法用于返回指定值的格式化表示。它由格式说明符处理,并将格式化字符串插入到字符串的占位符中。占位符可以使用数字索引 {0}、命名索引 {price} 甚至空 {} 来表示。format() 类似于“字符串格式”方法,这两种方法都调用对象的 __format__() 方法。


format(value[, format_spec]) #Where value can be a integer, float or binary format.

format() 参数

此函数接受两个参数:其中 format_spec 可以采用以下格式:

[[fill]align][sign][#][0][width][,][.precision][type]

其中,选项为
fill ::= 任意字符
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= 整数
precision ::= 整数
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

参数 描述 必需/可选
需要格式化的值 必需
format_spec 关于值应如何格式化的规范。 必需

format() 返回值

输入 返回值
格式说明符。 格式化表示

Python 中 format() 方法的示例

示例 1:使用 format() 进行数字格式化


# d, f and b are type

# integer
print(format(123, "d"))

# float arguments
print(format(123.4567898, "f"))

# binary format
print(format(12, "b"))
 

输出

123
123.456790
1100

示例 2:使用 fill、align、sign、width、precision 和 type() 进行数字格式化


# integer 
print(format(1234, "*>+7,d"))

# float number
print(format(123.4567, "^-09.3f"))
 

输出

*+1,234
0123.4570

示例 3:通过重写 __format__() 使用 format()


# custom __format__() method
class Person:
    def __format__(self, format):
        if(format == 'age'):
            return '23'
        return 'None'

print(format(Person(), "age"))
 

输出

23