Tutorial Study Image

Python center()

Python 中的 center() 函数有助于使字符串居中对齐。除了此函数,我们还可以指定字符串的宽度(包括填充字符)以及需要填充到缺失位置的字符。


string.center(width[, fillchar]) #where width is an integer number
 

center() 参数

center() 函数接受两个参数。如果缺少参数“fillchar”,它将默认使用空格(“ ”)。填充是在左侧和右侧进行的。

参数 描述 必需/可选
width 返回字符串的长度 必需
填充字符 填充字符 可选

center() 返回值

该方法返回一个居中对齐的字符串,具有指定的宽度并用给定的填充字符填充。它不修改原始字符串。

输入 返回值
如果参数 返回一个字符串 

Python 中 center() 方法的示例

示例 1:python center() 方法,带默认填充字符


string = "How are you?"

updated_string = string.center(24)

print("Centered String is: ", updated_string )
 

输出


Centered String is:     How are you?    

示例 2:Python center() 方法,带 * 填充字符


string = "How are you?"

updated_string = string.center(24, '*')

print("Centered String is: ", updated_string )
 

输出


Centered String is:  ***How are you?****