Python center

Python center 函数用于将字符串居中。使用指定的字符(默认为空格)填充剩余的宽度,并返回新的字符串。在本节中,我们将通过示例讨论如何编写字符串 center 函数。

Python 中的字符串 center 函数仅接受一个字符作为第二个参数,其语法为:

String_Value.center(Width, Char)
  • 宽度: 请指定字符串的对齐长度。
  • 字符: 此参数是可选的,如果您省略此参数,它将默认使用空格。要更改默认值,请指定您想在剩余宽度中使用的字符。

Python center 字符串函数示例

以下示例集可帮助您理解字符串 center 函数。对于 Str2,它会将字符串变量 Str1 居中,并用默认空格填充剩余宽度,然后打印输出。

您可能对空格感到困惑,因此我们将“=”用作第二个参数。此 Python Str3 语句用“=”符号填充剩余宽度。

center 函数返回新字符串中的输出,而不是更改原始字符串。要更改原始字符串,请编写以下语句。

Str1 = Str1.center()

字符串方法 只允许第二个参数为单个字符。让我们看看当我们在 Str4 和 Str5 变量中使用两个字符(即 + 和 *)时会发生什么。

从下面的图片中可以看到,它抛出了一个错误,提示:“TypeError:填充字符必须正好是一个字符长”。

Str1 = 'Tutorial Gateway'

Str2 = Str1.center(30)
print('Justify the string with White spaces is =', Str2)

Str3 = Str1.center(30, '=')
print("Justify the string with '=' using this is =", Str3)

# Observe the Original
print('Converted String is =', Str1.center(30, '='))
print('Original String is =', Str1)

# Performing it directly
Str4 = 'Tutorial Gateway'.center(30, '*')
print("Justify the string with '*' using it is =", Str4)

# Performing it with two characters
Str5 = 'Tutorial Gateway'.center(30, '+*')
print("Justify the string with '+' and '*' using it is =",Str5)
string Center function Example