Python provides the built-in capitalize() string method to convert the first character of a string to uppercase and automatically convert all remaining characters to lowercase. This method is commonly used in text formatting, data cleaning and preprocessing tasks where consistent capitalization is required. It does not modify the original string but returns a new formatted string.
- Converts the first character to uppercase
- Converts remaining characters to lowercase
- Works only on strings
- Returns a new string (original string remains unchanged)
Let's start with a simple example to understand the capitalize() functions:
s = "hello WORLD"
res = s.capitalize()
print(res)
Output
Hello world
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()
Return Value: A new string with the first character capitalized and all others in lowercase.
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
- 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
- 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.