python字符串填充(转)

ljust()方法返回字符串左对齐的字符串长度宽度。填充是通过使用指定的fillchar(默认为空格)。如果宽度小于len(s)返回原始字符串。
语法

以下是ljust()方法的语法:

str.ljust(width[, fillchar])

参数

  •     width -- 这是填充后字符串的总长度。
  •     fillchar -- 这是填充符,默认为空格。

返回值

此方法返回新字符串。填充是通过使用指定fillchar(默认为空格)。如果宽度小于len(s),返回原始字符串。

例子

下面的例子显示了ljust()方法的使用。

#!/usr/bin/python
str = "this is string example....wow!!!";
print str.ljust(50, '0');

当我们运行上面的程序,它会产生以下结果:

this is string example....wow!!!000000000000000000

同理,这些ljust、rjust、center方法都可以用

如:

>>> 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*****'

原文地址:https://www.cnblogs.com/shixisheng/p/7402691.html