python字符串-居中(center)


center方法使用填充字符对字符串进行填充,保持原字符串居中,默认填充字符是空格。

语法

center(width, fillchar=' ', /)

参数

  • width: 字符串的总长度。
  • fillchar: 填充字符,默认为空格。

返回值

  • 原字符串居中,长度为width的新字符串。

示例

str = 'abc'
# 注意前后使用空格填充
print('填充字符串到长度为5:', str.center(5))
print('填充字符串到长度为5,使用"*"号填充:', str.center(5, '*'))
# 原字符串长度为奇数,优先填充右边;原字符串长度为偶数,优先填充左边。
print('填充字符串到长度为4,优先填充右边:', str.center(4, '*'))
print('填充字符串到长度为5,优先填充左边:', 'abcd'.center(5, '*'))
print('填充字符串到长度为2,比原字符串长度小,字符串不变:', str.center(2, '*'))
填充字符串到长度为5:  abc 
填充字符串到长度为5,使用"*"号填充: *abc*
填充字符串到长度为4,优先填充右边: abc*
填充字符串到长度为5,优先填充左边: *abcd
填充字符串到长度为2,比原字符串长度小,字符串不变: abc

help()

Help on built-in function center:

center(width, fillchar=' ', /) method of builtins.str instance
    Return a centered string of length width.
    
    Padding is done using the specified fill character (default is a space).