The `capitalize()` function in Python is used to convert the first character of a string to uppercase and all other characters to lowercase.
Syntax
string.capitalize()
string: The string you want to capitalize.
Example
text = "hello world!" # Using capitalize() function capitalized_text = text.capitalize() print(capitalized_text)
Output
Hello world!
Explanation
– In the example above, the `capitalize()` function converts the first character of the string `”hello world!”` to uppercase, resulting in `”Hello world!”`.
– The rest of the string is converted to lowercase, but since the other letters are already lowercase, they remain unchanged.
Important Notes
– The `capitalize()` function only affects the first character of the string. It will not change the case of other characters unless they are uppercase.
– If the first character is already uppercase or if the string starts with a non-alphabetic character (like a digit or symbol), the string will remain unchanged except for the rest being converted to lowercase.
Example with Different Cases
text = "PYTHON programming" # Using capitalize() function capitalized_text = text.capitalize() print(capitalized_text)
Output
Python programming
In this case, the first letter “P” is capitalized, and the rest of the string is converted to lowercase, resulting in `”Python programming”`.