Capitalize Words
Capitalize the first letter of each word.
Word capitalization is essential for text formatting and data cleaning. This exercise teaches you how to process strings by splitting them into words, transforming each word, and reassembling the resultβa pattern used extensively in real-world applications.
π Concepts & Theory
Capitalizing words in a string is a common text formatting task. Python provides several built-in methods for this, but understanding manual implementation helps you grasp string manipulation fundamentals.
Built-in Methods:
1. title() Method
Capitalizes the first letter of each word:
text = "hello world"
result = text.title() # "Hello World"
2. capitalize() Method
Only capitalizes the first letter of the entire string:
text = "hello world"
result = text.capitalize() # "Hello world"
Manual Implementation Approach:
Split the string into words, capitalize each word's first letter, then rejoin:
words = text.split() # ["hello", "world"]
capitalized = [word[0].upper() + word[1:] for word in words]
result = " ".join(capitalized) # "Hello World"
Understanding String Methods:
split()divides string by whitespace into a listword[0]accesses the first characterupper()converts character to uppercaseword[1:]gets all characters from index 1 onwardsjoin()combines list elements with a separator
π― Your Challenge
Write capitalize_words without title().
π Starter Code
def capitalize_words(text):
pass
print(capitalize_words('hello world'))
- Split the string into individual words first
- Process each word separately
- Take the first character and make it uppercase
- Combine the uppercase first letter with the rest of the word
- Join all words back together with spaces
Solution
def capitalize_words(text):
words = text.split()
result = []
for word in words:
result.append(word[0].upper() + word[1:])
return ' '.join(result)
print(capitalize_words('hello world'))
Explanation
The solution splits the text into individual words using split(), then uses a list comprehension to capitalize each word. For each word, we take the first character with word[0], convert it to uppercase with upper(), and concatenate it with the rest of the word using word[1:]. Finally, join() reassembles the words with spaces. This demonstrates the powerful split-transform-join pattern. Time complexity: O(n) where n is the length of the string.
β οΈ Common Mistakes to Avoid
- Forgetting to handle empty strings
- Not checking if word has at least one character before accessing word[0]
- Using capitalize() which only capitalizes the first word
- Forgetting to rejoin the words after capitalization
- Not preserving multiple spaces between words