案例
某个字典存储了一系列属性值,
{
"lodDist": 100.0,
"SmallCull":0.04,
"DistCull":500.0,
"trilinear":40,
"farclip":477
}
在程序中,我们想以以下工整的格式将其内容输出,如何处理?
SmallCull : 0.04
farclip :477
lodDist :100.0
DistCull :500.0
trilinear :40
核心分析
(1)str.ljust(),str.rjust(),str.center(),进行左,右,居中对齐
(2)format()方法
代码
s = 'abc'
# ljust rjust center
ls = s.ljust(20, '=')
rs = s.rjust(20, '=')
cs = s.center(20, '=')
''' output
abc=================
=================abc
========abc=========
'''
s = 'abc'
# format
ls1 = format(s, '<20')
rs1 = format(s, '>20')
cs1 = format(s, '^20')
''' output
abc=================
=================abc
========abc=========
'''
# --------------------------
d = {
"lodDist": 100.0,
"SmallCull": 0.04,
"DistCull": 500.0,
"trilinear": 40,
"farclip": 477
}
ml = max(list(map(len, d.keys()))) # key中的字符串的最大长度,其中:max(list)求数组中的最大值
for k in d:
print(k.ljust(ml), ':', d[k])
'''output
SmallCull : 0.04
farclip : 477
lodDist : 100.0
trilinear : 40
DistCull : 500.0
'''