python string center() 方法用于根据给定的宽度将当前字符串定位在中心。此方法接受一个整数值,该值表示字符串的所需宽度作为参数,将当前字符串置于中心,并用空格填充字符串的其余字符。
默认情况下,字符串中的其余字符填充空格(前后),填充后的整个字符串作为输出返回,即居中值。您还可以使用 fillchar 可选参数指定需要用于填充的 charcat。
在下一节中,我们将了解有关 python 字符串 center() 方法的更多详细信息。
语法
以下是 python 字符串 center() 方法的语法。
str.center(width[, fillchar])
参数
以下是 python 字符串 center() 方法的参数。
- width − 此参数是一个整数值,表示字符串的总长度以及填充字符。
- fillchar − 此参数指定填充字符。仅接受单长度字符。默认填充字符是 ASCII 空格。
返回值
python string center() 方法返回以指定宽度居中的字符串值。
例以下是在 python string center() 函数的帮助下将输入字符串居中的示例。 在此程序中,将创建一个字符串 “Welcome to qikepu.” 。然后,在字符串上调用 center() 函数以使其居中,剩余的额外空格用指定为 '.' 的填充字符填充。使用 print() 函数打印输出。
str = "Welcome to qikepu."
output=str.center(40, '.')
print("The string after applying the center() function is:", output)
在执行上述程序时,将生成以下输出 -
例
如果将字母表作为填充字符,则输入字符串以给定的宽度居中,并使用 center() 函数的参数中指定的字母表填充额外的字符。
在以下示例中,将创建一个字符串 “Welcome to qikepu.” ,并在字符串上调用 center() 函数以将其居中到给定的宽度 '40',并使用 print() 函数打印输出。
str = "Welcome to qikepu."
output=str.center(40, 's')
print("The string after applying the center() function is:", output)
以下是执行上述程序得到的输出 -
例
如果未在 center() 函数的参数中指定 fillchar,则默认的 fillchar (ASCII 空格)将被视为填充值。
在下面的示例中,创建了一个字符串 “Welcome to qikepu.” ,并在字符串上调用 center() 函数以将其居中到给定的宽度 '40',但未在参数中指定 fillchar。使用 print() 函数打印输出。
str = "Welcome to qikepu."
output=str.center(40)
print("The string after applying the center() function is:", output)
通过执行上述程序获得以下输出 -
例
如果提到的参数宽度小于原始输入字符串的长度,则此函数不会修改原始字符串。
在下面的示例中,创建了一个字符串 “Welcome to qikepu.” ,并在字符串上调用 center() 函数,使其居中到给定的宽度 '5',该宽度小于创建的字符串的长度。然后使用 print() 函数打印输出。
str = "Welcome to qikepu."
output=str.center(5)
print("The string after applying the center() function is:", output)
上述程序在执行时显示以下输出 -
例
此函数不接受字符串 fillchar。它只接受一个字符 long fillchar。如果指定的 fillchar 不满足此条件,则会发生类型错误。
在下面的示例中,创建了一个字符串 “Welcome to qikepu.” ,并在该字符串上调用 center() 函数,使其居中到给定的宽度 '40' 和一个字符串 fillchar 'aa'。然后使用 print() 函数打印输出。
str = "Welcome to qikepu."
output=str.center(40, 'aa')
print("The string after applying the center() function is:", output)
上述程序的输出显示如下 -
File "main.py", line 2, in
output=str.center(40, 'aa')
TypeError: The fill character must be exactly one character long