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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 11 views 0 copies

Python code

18 lines
Python 3.9+
def 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

stdout
'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

  1. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.