python ljust,rjust,center,zfill对齐使用方法

时间:2022-06-27 22:03:24

字符串在输出时的对齐:
S.ljust(width,[fillchar]) 
#输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。 
S.rjust(width,[fillchar]) #右对齐 
S.center(width, [fillchar]) #中间对齐 
S.zfill(width) #把S变成width长,并在右对齐,不足部分用0补足

实例

 >>> str = "this is string example....wow!!!";
>>> str.ljust(50,'')
'this is string example....wow!!!000000000000000000'
>>> str.ljust(50)
'this is string example....wow!!! '
>>> str.rjust(50)
' this is string example....wow!!!'
>>> str.rjust(50,'')
'000000000000000000this is string example....wow!!!'
>>> str.center(50,'')
'000000000this is string example....wow!!!000000000'
>>> str.center(50)
' this is string example....wow!!! '
>>> str.zfill(50)
'000000000000000000this is string example....wow!!!'
>>>