Python String capitalize() 方法


Python String capitalize() 方法用于将当前字符串大写。它只返回一个字符串,其中第一个字母大写,即大写和 该字符串的其余字符将转换为小写字母。

如果输入字符串的第一个字母是非字母或已经是大写字母,则输出中将不起作用,即原始字符串不会被修改。

在本章中,我们将了解有关 python 字符串 capitalize() 方法的更多详细信息。

语法

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


 str.capitalize()

参数

此方法不接受任何参数。

返回值

此方法返回大写字符串作为其输出。

例

以下是 python 字符串 capitalize() 函数的示例。在这里,我们尝试将字符串 “Qikepucompoint” 的第一个字母大写。


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

在执行上述程序时,将生成以下输出 -

The resultant string is: Qikepucompoint.

例

如果输入字符串的第一个字母已经是大写字母,则 capitalize() 函数将返回当前字符串,不进行任何更改。

在下面的示例中,我们正在创建一个值为 “Qikepucompoint” 的字符串,因为它的第一个字符已经是一个大写字符,如果我们在这个字符串上调用 capitalize() 函数,它会返回当前字符串,没有任何变化。


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

以下是执行上述程序得到的输出 -

The resultant string is: Hii! welcome to Qikepucompoint.

例

如果输入字符串的第一个字母不是字母表,则此函数返回原始字符串。

在以下示例中,我们将创建一个字符串值,其中 “$” 作为第一个字符,并使用此字符串调用 capitalize() 函数。由于起始字母不是字母,因此此函数返回当前字符串,不进行任何更改。


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

通过执行上述程序获得以下输出 -

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

例

python 字符串 capitalize() 函数不会修改原始字符串。因此,如果打印它,则原始字符串将打印而不进行任何修改。


str = "hii! welcome to Qikepucom."
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 Qikepucom.
The original string is: hii! welcome to Qikepucom.

例

python 字符串 capitalize() 函数只将第一个字母大写。如果字符串中的其余字符包含大写字母,则它们都将更改为小写字母。


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

上述程序的输出显示如下 -

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