center()方法返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。
center()方法的语法为:
string.center(width[, fillchar])
center()参数
center()方法采用两个参数:
width- 填充后字符串的长度
fillchar (可选)-填充字符
fillchar参数是可选的。如果未提供,则将空格作为默认参数。
center()返回值
center()方法返回一个字符串,其中填充了指定的fillchar。它不会修改原始字符串。
示例1:fillchar参数为默认值的center()方法
string = "Python is awesome" new_string = string.center(24) print("填充后的字符串: ", new_string)
运行该程序时,输出为:
填充后的字符串: Python is awesome
示例2:fillchar为* 的center()方法
string = "Python is awesome" new_string = string.center(24, '*') print("填充后的字符串: ", new_string)
运行该程序时,输出为:
填充后的字符串: ***Python is awesome****