Python str.capitalize() function
str.capitalize()
Function in Python
The str.capitalize()
function in Python converts the first character of a string to uppercase and the rest of the characters to lowercase. This function is useful when you want to ensure the string starts with a capital letter, like in proper names or sentences.
Syntax:
string
: The string that you want to capitalize.
Example:
In this example:
- The string
"hello, world!"
becomes"Hello, world!"
, where only the first letter ('h'
) is capitalized and all other characters are converted to lowercase.
Example with mixed case:
Here:
- The first letter (
'p'
) is capitalized, and all other characters, including uppercase letters like'Y'
and'F'
, are converted to lowercase, resulting in"Python is fun!"
.
Example with numbers and special characters:
In this case:
- If the string starts with a number or special character,
capitalize()
leaves them unchanged and capitalizes the first alphabetic character that follows (if any). - Since the string starts with numbers here, no changes are made.
Key Points:
str.capitalize()
only affects the first alphabetic character by converting it to uppercase, and all subsequent characters are converted to lowercase.- It does not modify the original string but returns a new string with the applied changes.
- Non-alphabetic characters like digits, punctuation, and spaces are not affected. If the string starts with a non-alphabetic character, the first letter (if any) will still be capitalized.