Python 字串 capitalize() 方法



Python 字串 capitalize() 方法用於將當前字串的首字母大寫。它只返回一個字串,其中第一個字母大寫(即大寫),其餘字元轉換為小寫。

如果輸入字串的第一個字母是非字母字元,或者它已經是大寫字母,則輸出不會有任何影響,即原始字串不會被修改。

本章我們將學習更多關於 python 字串 capitalize() 方法的細節。

語法

以下是 python 字串 capitalize() 方法的語法。

str.capitalize()

引數

此方法不接受任何引數。

返回值

此方法返回大寫後的字串作為輸出。

示例

以下是 python 字串 capitalize() 函式的示例。在這裡,我們嘗試將字串 "tutorialspoint" 的首字母大寫。

str = "tutorialspoint"
output=str.capitalize()
print("The resultant string is:", output)

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

The resultant string is: Tutorialspoint.

示例

如果輸入字串的首字母已經是大寫字母,則 capitalize() 函式將返回當前字串,沒有任何更改。

在下面的示例中,我們建立了一個值為 "Tutorialspoint" 的字串,因為它的第一個字元已經是大寫字母,如果我們在此字串上呼叫 capitalize() 函式,它將返回當前字串,沒有任何更改。

str = "Hii! welcome to tutorialspoint."
output=str.capitalize()
print("The resultant string is:", output))

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

The resultant string is: Hii! welcome to tutorialspoint.

示例

如果輸入字串的首字母不是字母,則此函式將返回原始字串。

在下面的例子中,我們建立了一個以“$”作為首字元的字串值,並使用該字串呼叫了capitalize() 函式。由於起始字母不是字母,因此此函式返回當前字串,沒有任何更改。

str = "$Hii! welcome to tutorialspoint."
output=str.capitalize()
print("The resultant string is:", output)

執行上述程式後,得到以下輸出:

The resultant string is: $hii! welcome to tutorialspoint.

示例

Python 字串capitalize() 函式不會修改原始字串。因此,如果列印它,將列印原始字串,沒有任何修改。

str = "hii! welcome to tutorialspoint."
output=str.capitalize()
print("The string after applying the capitalize() function is:", output)
print("The original string is:", str)

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

The string after calling the capitalize() function: Hii! welcome to tutorialspoint.
The original string is: hii! welcome to tutorialspoint.

示例

Python 字串capitalize() 函式只將第一個字母大寫。如果字串中其餘字元包含大寫字母,則全部轉換為小寫字母。

   str = "hii! Welcome to TUTORIALSPOINT."
   output=str.capitalize()
   print("The string after applying the capitalize() function is:", output)

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

The string after calling the capitalize() function: Hii! welcome to tutorialspoint.
The original string is: hii! welcome to tutorialspoint.
python_strings.htm
廣告