How to Capitalize First Letter in Python: Simple Guide
In Python, you can capitalize the first letter of a string using the
str.capitalize() method. This method returns a new string with the first character in uppercase and the rest in lowercase.Syntax
The syntax to capitalize the first letter of a string is simple:
string.capitalize(): Returns a new string with the first character capitalized and the rest lowercase.
python
string.capitalize()
Example
This example shows how to use capitalize() to change the first letter of a string to uppercase.
python
text = "hello world" capitalized_text = text.capitalize() print(capitalized_text)
Output
Hello world
Common Pitfalls
One common mistake is expecting capitalize() to only change the first letter and keep the rest of the string unchanged. However, it converts all other letters to lowercase.
Also, capitalize() does not modify the original string because strings are immutable in Python.
python
text = "hELLO wORLD" # Wrong: expecting only first letter change capitalized_wrong = text.capitalize() print(capitalized_wrong) # Output: Hello world # Correct: if you want to keep the rest unchanged, use slicing capitalized_correct = text[0].upper() + text[1:] print(capitalized_correct) # Output: HELLO wORLD
Output
Hello world
HELLO wORLD
Quick Reference
Summary tips for capitalizing the first letter in Python:
- Use
str.capitalize()to capitalize first letter and lowercase the rest. - Use slicing with
str[0].upper() + str[1:]to capitalize first letter and keep the rest unchanged. - Remember strings are immutable; methods return new strings.
Key Takeaways
Use
str.capitalize() to capitalize the first letter and lowercase the rest of the string.If you want to keep the rest of the string unchanged, use slicing with
str[0].upper() + str[1:].Strings in Python are immutable; methods like
capitalize() return new strings without changing the original.Be aware that
capitalize() changes all letters except the first to lowercase.Always check for empty strings before using slicing to avoid errors.