Python String capitalize()
Method
The capitalize() method in Python is used to convert the first character of a string to uppercase and the rest to lowercase.
This method is useful when you want to format strings to look like proper sentences or names.
Syntax
string.capitalize()
Returns:
- A new string with the first character capitalized and the rest in lowercase.
Example 1: Basic Usage
text = "hello world"
print(text.capitalize())
Hello world
Example 2: All Caps to Capitalized
text = "PYTHON IS FUN"
print(text.capitalize())
Python is fun
Example 3: Already Capitalized
text = "Python programming"
print(text.capitalize())
Python programming
Example 4: Starting with Non-letter Character
text = "123hello"
print(text.capitalize())
123hello
Note: Only the first letter is affected. If the first character is not a letter, nothing changes.
Use Cases
- Formatting user input (e.g., names, titles)
- Creating proper sentence case for display
- Ensuring consistency in strings for comparisons
Does it Modify the Original String?
No. Strings in Python are immutable. capitalize()
returns a new string and does not change the original one.
Common Mistakes
- Assuming it capitalizes every word – it only affects the first character.
- For capitalizing every word, use
title()
instead.
Interview Tip
capitalize()
is often used in string normalization or preprocessing tasks before comparison or display.
Summary
capitalize()
returns a new string with the first character uppercase and the rest lowercase.- Original string remains unchanged.
- Non-letter first characters are not affected.
Practice Problem
Write a program that takes a sentence as input and prints the capitalized version.
sentence = input("Enter a sentence: ")
print("Capitalized:", sentence.capitalize())