Python String capitalize() Function
The String capitalize()
method returns a copy of the string with its first character capitalized and the rest lowercased.
The method does not change the original string.
Syntax
my_string.capitalize()
capitalize() Parameters
Python String capitalize()
function does not take any parameters.
capitalize() Return Value
Python String capitalize()
function returns a new string with the first character capitalized and the rest of the characters in lowercase.
Examples
Example 1: Capitalize a String with capitalize() method
The capitalize()
method is used to convert the first character of the sentence string to uppercase and the other characters to lowercase.
For example:
my_str = 'tUtORIALReFErEnCe'
result = my_str.capitalize()
print(result) # Output: Tutorialreference
output
Tutorialreference
Example 2: Capitalize a String with Non-Alphabetic First Character
If the string has first character that is non-alphabetic, the first character is kept unchanged while the rest of the string is changed to lowercase.
my_str = '123 Is A Number.'
result = my_str.capitalize()
print(result) # Output: 123 is a number.
output
123 is a number.
Example 3: capitalize() does Not Change the Original String
The capitalize()
method returns a new string and does not modify the original string.
For example:
my_str = 'tUtORIALReFErEnCe'
result = my_str.capitalize()
print(f"Before capitalize(): {my_str}") # Output: Before capitalize(): tUtORIALReFErEnCe
print(f"After capitalize(): {result}") # Output: After capitalize(): Tutorialreference
output
Before capitalize(): tUtORIALReFErEnCe
After capitalize(): Tutorialreference