Python 3 – String capitalize() Method
In Python, the capitalize()
method is used to convert the first character of a string to uppercase and the remaining characters to lowercase. This method does not modify the original string but instead returns a new string.
Syntax
string.capitalize()
The capitalize()
method does not accept any arguments. It only operates on the string that it is called on.
Examples
Let’s see some examples of the capitalize()
method in action:
# Example 1
string = "hello world"
capitalized_string = string.capitalize()
print(capitalized_string)
# Output: "Hello world"
# Example 2
string = "123abc"
print(string.capitalize())
# Output: "123abc"
# Example 3
string = " hello world "
print(string.capitalize())
# Output: " hello world "
In Example 1, the capitalize()
method is used to convert the first character of the string “hello world” to uppercase, resulting in the new string “Hello world”.
In Example 2, the capitalize()
method returns the same string since the first character of “123abc” is a digit, and digits cannot be capitalized.
In Example 3, the capitalize()
method returns the same string with the leading and trailing whitespaces preserved. This is because the capitalize()
method only deals with the first character of the string and does not modify the rest of the characters.
Using capitalize()
method with strings containing multiple words
When a string contains multiple words, the capitalize()
method only capitalizes the first word. To capitalize all the words in the string, we can use the title()
method instead.
# Example 1
string = "the quick brown fox"
capitalized_string = string.capitalize()
print(capitalized_string)
# Output: "The quick brown fox"
# Example 2
string = "the quick brown fox"
titlecased_string = string.title()
print(titlecased_string)
# Output: "The Quick Brown Fox"
In Example 1, only the first word “the” is capitalized since the capitalize()
method only operates on the first character of the string.
In Example 2, the title()
method is used to capitalize all the words in the string, resulting in “The Quick Brown Fox”.
Conclusion
The capitalize()
method is a useful method in Python to capitalize the first character of a string. However, it only operates on the first character of the string and does not modify the rest of the characters. When dealing with strings containing multiple words, we can use the title()
method to capitalize all the words in the string.