File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python
2+ # -*- encoding: utf-8 -*-
3+ """
4+ Topic: 对齐字符串
5+ Desc :
6+ """
7+
8+
9+ def align_str ():
10+ text = 'Hello World'
11+ print (text .ljust (20 ))
12+ print (text .rjust (20 ))
13+ print (text .center (20 ))
14+
15+ # 填充字符
16+ print (text .rjust (20 ,'=' ))
17+ print (text .center (20 ,'*' ))
18+
19+ # format函数
20+ print (format (text , '>20' ))
21+ print (format (text , '<20' ))
22+ print (format (text , '^20' ))
23+ # 同时增加填充字符
24+ print (format (text , '=>20s' ))
25+ print (format (text , '*^20s' ))
26+
27+ # 格式化多个值
28+ print ('{:=>10s} {:*^10s}' .format ('Hello' , 'World' ))
29+
30+ # 格式化数字
31+ x = 1.2345
32+ print (format (x , '=^10.2f' ))
33+
34+
35+ if __name__ == '__main__' :
36+ align_str ()
37+
Original file line number Diff line number Diff line change 55----------
66问题
77----------
8- todo...
8+ 你想通过某种对齐方式来格式化字符串
99
1010----------
1111解决方案
1212----------
13- todo...
13+ 对于基本的字符串对齐操作,可以使用字符串的ljust(), rjust()和center()方法。比如:
14+
15+ .. code-block :: python
16+
17+ >> > text = ' Hello World'
18+ >> > text.ljust(20 )
19+ ' Hello World '
20+ >> > text.rjust(20 )
21+ ' Hello World'
22+ >> > text.center(20 )
23+ ' Hello World '
24+ >> >
25+ 所有这些方法都能接受一个可选的填充字符。比如:
26+
27+ .. code-block :: python
28+
29+ >> > text.rjust(20 ,' =' )
30+ ' =========Hello World'
31+ >> > text.center(20 ,' *' )
32+ ' ****Hello World*****'
33+ >> >
34+
35+ 函数format()同样可以用来很容易的对齐字符串。
36+ 你要做的就是使用<,>或者^字符后面紧跟一个指定的宽度。比如:
37+
38+ .. code-block :: python
39+
40+ >> > format (text, ' >20' )
41+ ' Hello World'
42+ >> > format (text, ' <20' )
43+ ' Hello World '
44+ >> > format (text, ' ^20' )
45+ ' Hello World '
46+ >> >
47+
48+ 如果你想指定一个非空格的填充字符,将它写到对齐字符的前面即可:
49+
50+ .. code-block :: python
51+
52+ >> > format (text, ' =>20s' )
53+ ' =========Hello World'
54+ >> > format (text, ' *^20s' )
55+ ' ****Hello World*****'
56+ >> >
57+
58+ 当格式化多个值的时候,这些格式代码也可以被用在format()方法中。比如:
59+
60+ .. code-block :: python
61+
62+ >> > ' {:>10s } {:>10s } ' .format(' Hello' , ' World' )
63+ ' Hello World'
64+ >> >
65+
66+ format()函数的一个好处是它不仅适用于字符串。它可以用来格式化任何值,使得它非常的通用。
67+ 比如,你可以用它来格式化数字:
68+
69+ .. code-block :: python
70+
71+ >> > x = 1.2345
72+ >> > format (x, ' >10' )
73+ ' 1.2345'
74+ >> > format (x, ' ^10.2f' )
75+ ' 1.23 '
76+ >> >
77+
78+ |
1479
1580----------
1681讨论
1782----------
18- todo...
83+ 在老的代码中,你经常会看到被用来格式化文本的%操作符。比如:
84+
85+ .. code-block :: python
86+
87+ >> > ' %-20s ' % text
88+ ' Hello World '
89+ >> > ' %20s ' % text
90+ ' Hello World'
91+ >> >
92+
93+ 但是,在新版本代码中,你应该优先选择format()函数或者方法。
94+ format()要比%操作符的功能更为强大。并且,format()也比使用ljust(), rjust()或center()方法更通用,
95+ 因为它可以用来格式化任意对象,而不仅仅是字符串。
96+
97+ 如果想要完全了解format()函数的有用特性,
98+ 请参考 `在线Python文档 <https://docs.python.org/3/library/string.html#formatspec >`_
99+
You can’t perform that action at this time.
0 commit comments