python中ljust,rjust和center

Posted on 2019-11-07 19:28  Volcano3511  阅读(378)  评论(0编辑  收藏  举报

python中ljust,rjust和center

python中字符串的ljust、rjust、center方法讲解

这三种方法的用法差不多:S.ljust(width[, fillchar]),即长度加占位符,默认为空格,这三种在格式化输出时用着非常方便。

如:

>>> a="Hello world"

>>> print a.rjust(20)

'         Hello world'

>>> print a.ljust(20)

'Hello world         '

>>> print a.center(20)

'    Hello world     '

>>> print a.rjust(20,'*')

'*********Hello world'

>>> print a.ljust(20,'*')

'Hello world*********'

>>> print a.center(20,'*')

'****Hello world*****'

注:如果width小于字符串的长度,则完整输出字符串