Python String capitalize() Method
The str.capitalize()
method capitalize (converts to titlecase) the first character of the string and keeps all the other characters in lowercase.
Note: From Python 3.8 onwards, the first character is converted into titlecase instead of uppercase. This means the digraphs will only have the first letter capitalized instead of the full character.
Example:
text ="python Is BEST"
captialized_text= text.capitalize()
print(captialized_text)
Output
Python is best
Syntax
The Syntax of the str.capitalize()
function is:
str.capitalize()
Here, str
is a string.
Parameters
The str.capitalize()
function does not take any parameters.
Return Value
The str.capitalize()
function returns the copy of a string with its first letter capitalized and the rest of it in lowercase.
Example 1: Python Program to capitalize a string
In the below example, the capitalize()
converts the first character of the text
to uppercase and keeps the rest in lowercase. Notice certain uppercase characters in the value of text
variable are converted to lowercase.
text ="welcome to PYTHON Tutorial"
# capitalizes the first letter in string
# and keeps the rest of the string in lowercase
captialized_text= text.capitalize()
print(captialized_text)
Output
Welcome to python tutorial
Example 2: capitalize() method when a first character is a number, special character, or uppercase
In case if the string starts with an uppercase, number or special character, the first character will be kept as-is, and the rest of the characters in the string will be lowered.
# if the first character of the string is a number
text1 = "2022 YEAR Is Awesome"
print(text1.capitalize())
# if the first character of the string is uppercase
text2= "PYTHON PROGRAMMING"
print(text2.capitalize())
# if the first character of the string is a special character
text3="_special_CHAR@CTER$"
print(text3.capitalize())
Output
2022 year is awesome
Python programming
_special_characters
Reference: Python Official Docs