在本教程中,我们将借助示例了解 Python format() 函数。
format() 方法返回由格式说明符控制的给定值的格式化表示。
示例
value = 45
# format the integer to binary
binary_value = format(value, 'b')
print(binary_value)
# Output: 101101
format() 语法
它的语法是:
format(value[, format_spec])
参数:
format() 函数有两个参数:
- value- 需要格式化的值
- format_spec- 值应如何格式化的规范。
格式说明符可以是以下格式:
[[fill]align][sign][#][0][width][,][.precision][type] where, the options are fill ::= any character align ::= "<" | ">" | "=" | "^" sign ::= "+" | "-" | " " width ::= integer precision ::= integer type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
访问这些链接以了解有关 format types 和 alignment 的更多信息。
返回:
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:带有填充、对齐、符号、宽度、精度和类型的数字格式
# integer
print(format(1234, "*>+7,d"))
# float number
print(format(123.4567, "^-09.3f"))
输出
*+1,234 0123.4570
在这里,当格式化整数 1234 时,我们指定了格式化说明符 *>+7,d 。让我们了解每个选项:
*- 格式化后填充空格的填充字符>- 右对齐选项,将输出字符串右对齐+- 这是强制数字签名的符号选项(左侧有一个符号)7- 宽度选项强制数字的最小宽度为 7,其他空格将由填充字符填充,- 千位运算符在所有千位之间放置逗号。d- 指定数字是整数的类型选项。
在格式化浮点数 123.4567 时,我们指定了格式说明符 ^-09.3f 。这些是:
^- 将输出字符串与剩余空间的中心对齐的中心对齐选项-- 这是强制仅负数显示符号的符号选项0- 它是放置在空格位置的字符。9- 设置数字最小宽度为9的宽度选项(包括小数点、千位逗号和符号).3- 将给定浮点数的精度设置为 3 位的精度运算符f- 这是指定数字是浮点数的类型选项。
示例 3:通过覆盖 __format__() 来使用 format()
# custom __format__() method
class Person:
def __format__(self, format):
if(format == 'age'):
return '23'
return 'None'
print(format(Person(), "age"))
输出
23
在这里,我们重写了类 Person 的 __format__() 方法。
它现在接受 format 参数,如果等于 'age' 则返回 23。如果未指定格式,则返回None。
format() 函数在内部运行 Person().__format__("age") 以返回 23。
内置format() 对比。字符串format()
format() 函数类似于String format 方法。在内部,这两种方法都调用对象的__format__() 方法。
虽然内置的format() 函数是在内部使用__format__() 格式化对象的低级实现,但字符串format() 是能够对多个对象字符串执行复杂格式化操作的高级实现。
相关用法
- Python format()用法及代码示例
- Python calendar formatmonth()用法及代码示例
- Python calendar formatyear()用法及代码示例
- Python focus_set() and focus_get()用法及代码示例
- Python dict fromkeys()用法及代码示例
- Python frexp()用法及代码示例
- Python float转exponential用法及代码示例
- Python calendar firstweekday()用法及代码示例
- Python fsum()用法及代码示例
- Python filecmp.cmpfiles()用法及代码示例
- Python float()用法及代码示例
- Python fileinput.filelineno()用法及代码示例
- Python fileinput.lineno()用法及代码示例
- Python fileinput.input()用法及代码示例
- Python factorial()用法及代码示例
- Python fabs() vs abs()用法及代码示例
- Python fileinput.isfirstline()用法及代码示例
- Python frozenset()用法及代码示例
- Python string find()用法及代码示例
注:本文由纯净天空筛选整理自 Python format()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
