center()
方法返回一个经过指定字符填充后的居中字符串。
示例
sentence = "Python is awesome"
# returns the centered padded string of length 24
new_string = sentence.center(24, '*')
print(new_string)
# Output: ***Python is awesome****
center() 语法
center()
方法的语法是
str.center(width, [fillchar])
这里,str
是一个字符串。
center() 参数
center()
方法接受两个参数
- width - 包含填充字符的字符串长度
- fillchar (可选) - 填充字符
注意:如果未提供 fillchar,则默认使用空格。
center() 返回值
center()
方法返回
- 一个用指定 fillchar 填充的字符串
注意: center()
方法不会修改原始字符串。
示例 1:Python center()
sentence = "Python is awesome"
# returns the centered padded string of length 20
new_string = sentence.center(20, '$')
print(new_string)
输出
$Python is awesome$$
在上面的示例中,我们将 center()
方法与 sentence 字符串一起使用,形式为 sentence.center(20,'$')
。
该方法返回一个新的居中字符串,将句子用 '$'
填充到长度为 20。
示例 2:center() 与默认参数
text = "Python is awesome"
# returns padded string by adding whitespace up to length 24
new_text = text.center(24)
print("Centered String: ", new_text)
输出
Centered String: Python is awesome
这里,我们没有在 center()
方法中传入 fillchar 参数。该方法用空格填充 text,使居中字符串的长度为 24。
另请阅读