Python字串center()方法



Python字串center()方法用於根據給定的寬度將當前字串定位在中心。此方法接受一個整數作為引數,表示字串的所需寬度,將當前字串放置在中心,並用空格填充字串的其餘字元。

預設情況下,字串中剩餘的字元用空格填充(前面和後面),並且填充後的整個字串作為輸出返回,即居中值。您也可以使用可選引數fillchar指定要用於填充的字元。

在下一節中,我們將學習更多關於Python字串center()方法的細節。

語法

以下是Python字串center()方法的語法。

str.center(width[, fillchar])

引數

以下是Python字串center()方法的引數。

  • width − 此引數是一個整數,表示字串以及填充字元的總長度。

  • fillchar − 此引數指定填充字元。只接受單個長度的字元。預設填充字元是ASCII空格。

返回值

Python字串center()方法返回在指定寬度內居中的字串值。

示例

以下是如何使用Python字串center()函式居中輸入字串的示例。在這個程式中,建立一個字串"Welcome to Tutorialspoint."。然後,在字串上呼叫center()函式將其居中,其餘多餘的空格用指定的填充字元'.'填充。輸出使用print()函式列印。

str = "Welcome to Tutorialspoint."
output=str.center(40, '.')
print("The string after applying the center() function is:", output)

執行上述程式後,將生成以下輸出 -

The string after applying the center() function is: .......Welcome to Tutorialspoint........

示例

如果將字母作為填充字元,則輸入字串將在給定的寬度內居中,並且多餘的字元將使用在center()函式引數中指定的字母進行填充。

在以下示例中,建立一個字串"Welcome to Tutorialspoint.",並在字串上呼叫center()函式將其居中到給定的寬度'40',輸出使用print()函式列印。

str = "Welcome to Tutorialspoint."
output=str.center(40, 's')
print("The string after applying the center() function is:", output)

執行上述程式後,將獲得以下輸出 -

The string after applying the center() function is: sssssssWelcome to Tutorialspoint.sssssss

示例

如果在center()函式的引數中未指定fillchar,則預設fillchar(即ASCII空格)將被視為填充值。

在以下示例中,建立一個字串"Welcome to Tutorialspoint.",並在字串上呼叫center()函式將其居中到給定的寬度'40',但在引數中未指定fillchar。輸出使用print()函式列印。

str = "Welcome to Tutorialspoint."
output=str.center(40)
print("The string after applying the center() function is:", output)

執行上述程式後,將獲得以下輸出 -

The string after applying the center() function is:        Welcome to Tutorialspoint.       

示例

如果引數width小於原始輸入字串的長度,則此函式不會修改原始字串。

在下面的示例中,建立了一個字串“Welcome to Tutorialspoint.”,並呼叫字串的center()函式將其居中到給定的寬度'5',該寬度小於建立的字串的長度。然後使用print()函式列印輸出。

str = "Welcome to Tutorialspoint."
output=str.center(5)
print("The string after applying the center() function is:", output)

上述程式執行後,顯示以下輸出:

The string after applying the center() function is: Welcome to Tutorialspoint.

示例

此函式不接受字串fillchar。它只接受一個字元長的fillchar。如果指定的fillchar不滿足此條件,則會發生型別錯誤。

在下面的示例中,建立了一個字串“Welcome to Tutorialspoint.”,並呼叫字串的center()函式將其居中到給定的寬度'40'和字串fillchar 'aa'。然後使用print()函式列印輸出。

str = "Welcome to Tutorialspoint."
output=str.center(40, 'aa')
print("The string after applying the center() function is:", output)

上述程式的輸出顯示如下:

Traceback (most recent call last):
  File "main.py", line 2, in 
    output=str.center(40, 'aa')
TypeError: The fill character must be exactly one character long
python_strings.htm
廣告