# -*- coding:utf-8 -*-
"""
实际案例:
某个字典存储了一系列属性值,
{
"lodDist":100.0,
"SmallCull":0.04,
"DistCull":500.0,
"farclip":477
}
在程序中,我们想以以下工整的格式将其内容输出,如何处理?
SmallCull :0.04
farclip :477
lodDist :100.0
DistCull :500.0
解决方案:
方法一:使用字符串的str.ljust(), str.rjust(), str.center()进行左,右,居中对齐.
方法二:使用format()方法,传递类似'<20', '>20', '^20'参数完成同样任务.
"""
s = 'abc'
# ljust(width=, fillchar=)
# format(value=, format_spec=)
format(s, '<20') # < 描述左对齐
format(s, '>20') # > 右对齐
format(s, '^20') # ^ 居中
d = {
"lodDist":100.0,
"SmallCull":0.04,
"DistCull":500.0,
"farclip":477
}
w = max(map(len, d.keys()))
for k in d:
print k.ljust(w), ':', d[k]
4-5对字符串进行左,右,居中对齐
最新推荐文章于 2023-10-13 18:37:54 发布