titlecase
The `titlecase` library is a Python port of John Gruber's `titlecase.pl` script (version 2.4.1). It provides a more intelligent and stylistically correct title-casing function than Python's built-in `str.title()` method. It applies rules from the New York Times Manual of Style, handling 'small words' (like articles, conjunctions, and prepositions) and employing heuristics for abbreviations, aiming for publication-ready titles. The library maintains an active status with updates occurring as needed for bug fixes or minor enhancements.
Warnings
- gotcha Do not confuse with Python's built-in `str.title()` method. The built-in method capitalizes the first letter of *every* word, including small words (e.g., 'a', 'an', 'the', 'of') and incorrectly handles apostrophes (e.g., 'it's' becomes 'It'S'). The `titlecase` library is designed to address these common stylistic inaccuracies for proper title casing.
- gotcha The library's title-casing rules are primarily based on American English (New York Times Manual of Style) and use regex heuristics. This means it might not perfectly handle complex linguistic nuances, non-standard abbreviations, or phrases in other languages or specific non-American English contexts.
Install
-
pip install titlecase
Imports
- titlecase
from titlecase import titlecase
Quickstart
from titlecase import titlecase
# Basic usage
text_input = "the quick brown fox jumps over the lazy dog"
title_cased_text = titlecase(text_input)
print(f"Original: '{text_input}'")
print(f"Title cased: '{title_cased_text}'")
# With a custom callback for abbreviations
def custom_abbreviations(word, **kwargs):
if word.upper() in ('TCP', 'UDP'):
return word.upper()
return None # Return None to let titlecase process normally
tech_phrase = 'a simple tcp and udp wrapper'
formatted_tech_phrase = titlecase(tech_phrase, callback=custom_abbreviations)
print(f"Original (tech): '{tech_phrase}'")
print(f"Formatted (tech): '{formatted_tech_phrase}'")