Python3 如何对字符串进行左、右和居中对齐,str.ljust,str.rjust,str.center,str.format
发布时间:2017-11-22T09:12:27:手机请访问
实际案例
某个字典存储了一系列属性值,
{
"lodDist": 100.0,
"SmallCull": 0.04,
"DistCull": 500.0,
"trilinear": 40,
"farclip": 477
}
在程序中,我们想以如下工整的格式将其内容输出,如何处理?
SmallCull : 0.04
lodDist : 100.0
DistCull : 500.0
trilinear : 40
farclip : 477
看到这里大部分人会想到:
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 |
In [1]: s = 'abc' In [2]: s.ljust? Docstring: S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). Type: builtin_function_or_method In [3]: s.ljust(20) Out[3]: 'abc ' In [4]: s.rjust(20) Out[4]: ' abc' In [5]: s.center? Docstring: S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) Type: builtin_function_or_method In [6]: s.center(20) Out[6]: ' abc ' |
还有一种就是format
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
In [7]: format? Signature: format(value, format_spec='', /) Docstring: Return value.__format__(format_spec) format_spec defaults to the empty string Type: builtin_function_or_method In [8]: format(s,'<20') Out[8]: 'abc ' In [9]: format(s,'>20') Out[9]: ' abc' In [10]: format(s,'^20') Out[10]: ' abc ' |
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 |
# -*- coding: utf-8 -*- __author__ = 'songhao' d = { "lodDist": 100.0, "SmallCull": 0.04, "DistCull": 500.0, "trilinear": 40, "farclip": 477 } # 先获取最大长度 w = max(map(len, d.keys())) print("第一种方法:") for x in d.keys(): print(x.ljust(w), ':', d[x]) print("第二种方法:") for x in d.keys(): print(format(x, "<"+str(w)), ':', d[x]) ####out## # 第一种方法: # lodDist : 100.0 # SmallCull : 0.04 # DistCull : 500.0 # trilinear : 40 # farclip : 477 # 第二种方法: # lodDist : 100.0 # SmallCull : 0.04 # DistCull : 500.0 # trilinear : 40 # farclip : 477 |
