python的format打印格式'{0:2d} @ {1:2d} {2}{0:<2d}'的含义

发布时间 2023-08-14 15:56:44作者: wenxpplus
# BEGIN BISECT_DEMO
import bisect
import sys

HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]

ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'

def demo(bisect_fn):
for needle in reversed(NEEDLES):
position = bisect_fn(HAYSTACK, needle) # <1>
offset = position * ' |' # <2>
print(ROW_FMT.format(needle, position, offset)) # <3>

if __name__ == '__main__':

if sys.argv[-1] == 'left': # <4>
bisect_fn = bisect.bisect_left
else:
bisect_fn = bisect.bisect

print('DEMO:', bisect_fn.__name__) # <5>
print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK))
demo(bisect_fn)

 

这段代码,有个地方不太理解为啥,打印的时候传参传了3个,打印的值实际只有3个,后面百度了下format的用法才理解

ROW_FMT = '{0:2d} @ {1:2d}    {2}{0:<2d}'

1、{0:2d}表示的是取第一个值,d表示数字,2表示2位数
2、{0:<2d}同上,区别是<表示的左对齐