Transforming a list of strings, such as standardizing names, titles, or labels, is a common data cleaning task. Python provides several string methods for different capitalization needs.
Using List Comprehension
The standard Pythonic approach combines list comprehension with string methods:
names = ['alice', 'bob', 'charlie']
capitalized = [name.capitalize() for name in names]
print(capitalized)Output:
['Alice', 'Bob', 'Charlie']Handling Mixed Case Input
The capitalize() method intelligently handles irregular input:
messy_names = ['aLICE', 'BOB', 'cHaRlIe']
cleaned = [name.capitalize() for name in messy_names]
print(cleaned)Output:
['Alice', 'Bob', 'Charlie']Using map() for Performance
For very large lists, map() can be slightly faster as it pushes the loop into optimized C code:
names = ['alice', 'bob', 'charlie']
capitalized = list(map(str.capitalize, names))
print(capitalized)Output:
['Alice', 'Bob', 'Charlie']Multi-Word Strings with title()
The capitalize() method only affects the first letter of the entire string. For multi-word strings like names or locations, use title():
cities = ['new york', 'los angeles', 'san francisco']
print([city.capitalize() for city in cities])
print([city.title() for city in cities])Output:
['New york', 'Los angeles', 'San francisco']
['New York', 'Los Angeles', 'San Francisco']Uppercase and Lowercase
For complete case transformations:
words = ['Hello', 'World', 'Python']
print([word.upper() for word in words])
print([word.lower() for word in words])Output:
['HELLO', 'WORLD', 'PYTHON']
['hello', 'world', 'python']Handling Edge Cases
Real-world data often contains empty strings, whitespace, or None values:
def safe_capitalize(items: list) -> list:
"""Capitalize strings, handling None and empty values."""
result = []
for item in items:
if item is None:
result.append(None)
elif isinstance(item, str):
result.append(item.strip().capitalize())
else:
result.append(item)
return result
data = ['alice', ' bob ', '', None, 'CHARLIE']
cleaned = safe_capitalize(data)
print(cleaned)Output:
['Alice', 'Bob', '', None, 'Charlie']Using a Conditional Expression
A more concise approach:
names = ['alice', '', 'bob', None, 'charlie']
capitalized = [
name.capitalize() if name else name
for name in names
]
print(capitalized)Output:
['Alice', '', 'Bob', None, 'Charlie']Custom Capitalization Rules
Sometimes you need specific capitalization patterns:
def smart_capitalize(text: str) -> str:
"""Capitalize with exceptions for small words."""
small_words = {'a', 'an', 'the', 'and', 'but', 'or', 'for', 'of', 'to'}
words = text.lower().split()
result = []
for i, word in enumerate(words):
if i == 0 or word not in small_words:
result.append(word.capitalize())
else:
result.append(word)
return ' '.join(result)
titles = [
'the lord of the rings',
'a tale of two cities',
'war and peace'
]
formatted = [smart_capitalize(title) for title in titles]
for title in formatted:
print(title)Output:
The Lord of the Rings
A Tale of Two Cities
War and PeaceSwap Case
To invert the case of each character:
words = ['Hello', 'World']
swapped = [word.swapcase() for word in words]
print(swapped)Output:
['hELLO', 'wORLD']Method Comparison
| Method | Input | Output | Use Case |
|---|---|---|---|
.capitalize() |
hello world |
Hello world |
Sentences, single words |
.title() |
hello world |
Hello World |
Names, titles, locations |
.upper() |
hello world |
HELLO WORLD |
Acronyms, emphasis |
.lower() |
HELLO WORLD |
hello world |
Normalization |
.swapcase() |
Hello World |
hELLO wORLD |
Special formatting |
Summary
- Use
.capitalize()for single words or sentence-style capitalization. - Use
.title()for multi-word strings like names or titles. - Use list comprehension for readability:
[x.capitalize() for x in items]. - Use
map()for large datasets:list(map(str.capitalize, items)). - Handle edge cases like None, empty strings, and whitespace in production code.