一覧の可読性を向上させるための小道具。
Python
def format_list(data, *, width=16, prefix='',
datafmt='%s', msgfmt='%#s', separator=',', space=1, suffix='\n'):
space = ' ' * space
fmtdata = [datafmt % d for d in data]
msgfmt = msgfmt.replace('#', str(max(len(s) for s in fmtdata)))
msglist = [(msgfmt % d) + separator for d in fmtdata]
return ''.join((prefix + space.join(msglist[i:i+width]) + suffix)
for i in range(0, len(msglist), width))
Python
print(format_list(range(44)))
print(format_list(range(44), msgfmt='%-#s', space=2, prefix=(' ' * 4)))
print(format_list(range(44), datafmt='%#04x', width=8))
結果
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2a, 0x2b,