How to Truncate a String with Ellipsis in Python
A function that shortens text to a maximum length and appends an ellipsis when truncation occurs, handling edge cases.
Python code
18 linesdef truncate_with_ellipsis(text: str, max_length: int) -> str:
"""Truncate text to max_length, appending ellipsis if truncated."""
if len(text) <= max_length:
return text
if max_length <= 3:
return text[:max_length]
return text[: max_length - 3] + "..."
if __name__ == "__main__":
test_cases = [
("Hello, world!", 10),
("Python", 10),
("Truncation test case", 8),
("Short", 3),
("abcdef", 3),
]
for text, max_len in test_cases:
print(f"{text!r} at {max_len} -> {truncate_with_ellipsis(text, max_len)!r}")
Output
'Hello, world!' at 10 -> 'Hello worl...'
'Python' at 10 -> 'Python'
'Truncation test case' at 8 -> 'Truncat...'
'Short' at 3 -> 'Sho'
'abcdef' at 3 -> 'abc'
How it works
The function first checks if the text fits within the limit and returns it unchanged when it does. For longer text, it reserves 3 characters for the ellipsis and slices the original string accordingly. The edge case of max_length <= 3 prevents slicing with negative indices, which would produce incorrect results. Using string slicing text[:max_length - 3] is efficient and readable. The function preserves the original string type and handles all standard text inputs gracefully.
Common mistakes
- Forgetting to handle `max_length <= 3` which causes negative slice indices
- Using `max_length - 3` without checking if the result is positive
- Appending the ellipsis even when the text fits within the limit
- Not accounting for ellipsis length in the total character count
Variations
- Use `textwrap.shorten(text, width=max_length, placeholder='...')` for the same effect with configurable placeholder
Real-world use cases
- Displaying truncated file names or titles in a UI list view when the full name exceeds the column width.
- Logging truncated error messages to keep log lines within a fixed character budget for better readability.
- Creating preview text snippets for search results or article cards without exceeding layout constraints.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.