【文件属性】:
文件名称:字符串对齐-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2021-06-10 05:19:14
python cookbook 第3版 高清 中文完整版
2.13 字符串对齐
问题
你想通过某种对齐方式来格式化字符串
解决方案
对于基本的字符串对齐操作,可以使用字符串的 ljust() , rjust() 和 center() 方法。
比如:
>>> text = 'Hello World'
>>> text.ljust(20)
'Hello World '
>>> text.rjust(20)
' Hello World'
>>> text.center(20)
' Hello World '
>>>
所有这些方法都能接受一个可选的填充字符。比如:
>>> text.rjust(20,'=')
'=========Hello World'
>>> text.center(20,'*')
'****Hello World*****'
>>>
函数 format() 同样可以用来很容易的对齐字符串。 你要做的就是使用 <,> 或者 ^ 字符
后面紧跟一个指定的宽度。比如: