看到这么奇怪的占位符,估计都是一脸懵逼。而且网上搜不到。
其实很简单,试一下就知道了。
print("{0:2}".format(10, 20, 30, 40))
# 10
# 1
print("{:2}: {}".format(1, 2, 3, 4))
# 1: 2
通过简单是打印就明白了:
{0:2}
表示的是一个占位符{0:2}
表示至少占两个位,前面是一个空格。显示的效果为x
, 其中x
是被打印的内容。- 为了方便,可以省略0,直接表示为
{:2}
。
更实用的 格式化 {:02} ,最少显示2个字符长度,前面不够的部分全部补0, 超过的部分忽略不计。
# 当然这里肯定可以是 {0:3}, {0:4}
print("{:05}".format(11)) # 输出 00011
print("{:02}".format(0)) # 输出 00
print("{:02}".format(7)) # 输出 07
print("{:02}".format(95)) # 输出 95
print("{:02}".format(91225)) # 输出 91225
不过这里也不能乱写,比如 {:-5}, {:x3} 这样都会报错,只有补零这个是有效的。
输出:
00011
00
07
95
91225
比如现在是7点钟,但是可能希望显示的字符串是"07", 那么,这个字符串的格式化就非常方便了,不然还得自己去判断数字的大小,然后动态去补0.
Note When formatting a number (int, float, complex, decimal.Decimal and subclasses) with the n type (ex: ‘{:n}’.format(1234)), the function temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale to decode decimal_point and thousands_sep fields of localeconv() if they are non-ASCII or longer than 1 byte, and the LC_NUMERIC locale is different than the LC_CTYPE locale. This temporary change affects other threads.
https://docs.python.org/3/library/stdtypes.html#str.format