String capitalize() Method in Python
The capitalize() method in Python is used to change the first letter of a string to uppercase and make all other letters lowercase. It is especially useful when we want to ensure that text follows title-like capitalization, where only the first letter is capitalized.
Let's start with a simple example to understand the capitalize() functions:
s = "hello WORLD"
res = s.capitalize()
print(res)
Output
Hello world
Explanation: In this example, capitalize() method converts the first character "h" to uppercase and change the rest of characters to lowercase.
Syntax of capitalize() Method
s.capitalize()
Parameters:
- None
Return Value: A new string with the first character capitalized and all others in lowercase.
Note: The original string remains unchanged (strings are immutable in Python).
Examples of capitalize() Method
Example 1: Multiple Words
The capitalize() method only affects the first letter of the string and doesn’t capitalize each word in multi-word strings.
s = "multiple WORDS IN a String"
res = s.capitalize()
print(res)
Output
Multiple words in a string
Explanation:
- Only the first character of the entire string is capitalized.
- All other letters are lowercased.
- capitalize() does not capitalize each word individually (unlike title()).
Example 2: When the First Character is a Number
When the first character of a string is a number, capitalize() method does not alter it because it only affects alphabetical characters. Instead, it will simply convert any following alphabetical characters to lowercase.
s = "123hello WORLD"
res = s.capitalize()
print(res)
Output
123hello world
Explanation:
- Since the first character is a number, it’s left unchanged.
- The rest of the string is still lowercased.
- capitalize() skips non-alphabet characters for capitalization.
Related Article: