format() 方法用于返回指定值的格式化表示。它由格式说明符处理,并将格式化字符串插入到字符串的占位符中。占位符可以使用数字索引 {0}、命名索引 {price} 甚至空 {} 来表示。format() 类似于“字符串格式”方法,这两种方法都调用对象的 __format__() 方法。
format(value[, format_spec]) #Where value can be a integer, float or binary 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 | 关于值应如何格式化的规范。 | 必需 |
| 输入 | 返回值 |
|---|---|
| 格式说明符。 | 格式化表示 |
# 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
# integer
print(format(1234, "*>+7,d"))
# float number
print(format(123.4567, "^-09.3f"))
输出
*+1,234 0123.4570
# custom __format__() method
class Person:
def __format__(self, format):
if(format == 'age'):
return '23'
return 'None'
print(format(Person(), "age"))
输出
23