Python center()

python 中的center()函数有助于使字符串居中对齐。伴随着这个函数,我们可以指定包含填充字符的字符串的宽度,以及需要在缺少的地方填充哪个字符。

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

中心()参数:

center()函数接受两个参数。如果缺少参数“fillchar ”,它将使用空格(" ")作为默认值。填充在左侧和右侧完成。

参数 描述 必需/可选
宽度 返回字符串的长度 需要
菲勒 插入字符 可选择的

中心()返回值

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

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

Python 中center()方法的示例

示例 1:默认为 fillchar 的 python center()方法

 string = "How are you?"

updated_string = string.center(24)

print("Centered String is: ", updated_string ) 

输出:

 Centered String is:     How are you? 

示例 2:带有* fillchar 的 Python center()方法

 string = "How are you?"

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

print("Centered String is: ", updated_string ) 

输出:

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

你可能感兴趣的