🔍 Code Extractor

function truncate_text

Maturity: 56

Truncates a text string to a specified maximum length and appends a suffix if truncation occurs.

File:
/tf/active/vicechatdev/CDocs/utils/__init__.py
Lines:
228 - 242
Complexity:
simple

Purpose

This function is designed to shorten long text strings to fit within a specified character limit, commonly used for displaying previews, summaries, or fitting text into UI elements with space constraints. It intelligently accounts for the suffix length to ensure the total output doesn't exceed the maximum length.

Source Code

def truncate_text(text: str, max_length: int = 100, suffix: str = "...") -> str:
    """
    Truncate text to maximum length.
    
    Args:
        text: Text to truncate
        max_length: Maximum length
        suffix: Suffix to add if truncated
        
    Returns:
        Truncated text
    """
    if len(text) <= max_length:
        return text
    return text[:max_length - len(suffix)] + suffix

Parameters

Name Type Default Kind
text str - positional_or_keyword
max_length int 100 positional_or_keyword
suffix str '...' positional_or_keyword

Parameter Details

text: The input string to be truncated. Can be any text of any length. No constraints on content or encoding.

max_length: The maximum number of characters allowed in the output string, including the suffix. Must be a positive integer. Default is 100. If the original text length is less than or equal to this value, no truncation occurs.

suffix: The string to append at the end of truncated text to indicate truncation has occurred. Default is '...' (ellipsis). Common alternatives include '…', ' [more]', or custom indicators. The suffix length is subtracted from max_length to determine where to cut the text.

Return Value

Type: str

Returns a string that is either the original text (if its length is <= max_length) or a truncated version. The truncated version will have exactly max_length characters, consisting of the first (max_length - len(suffix)) characters of the original text followed by the suffix. The return type is always str.

Usage Example

# Basic usage with defaults
text = "This is a very long text that needs to be truncated for display purposes"
result = truncate_text(text)
print(result)  # Output: 'This is a very long text that needs to be truncated for display purposes' (if <= 100 chars)

# Truncate with custom max_length
long_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore."
short = truncate_text(long_text, max_length=50)
print(short)  # Output: 'Lorem ipsum dolor sit amet, consectetur adipi...'

# Custom suffix
result = truncate_text(long_text, max_length=50, suffix=" [read more]")
print(result)  # Output: 'Lorem ipsum dolor sit amet, consect [read more]'

# Text shorter than max_length (no truncation)
short_text = "Hello"
result = truncate_text(short_text, max_length=100)
print(result)  # Output: 'Hello'

Best Practices

  • Ensure max_length is greater than the length of the suffix to avoid negative slicing or unexpected results
  • Consider using a suffix length of at least 3 characters (like '...') for clear indication of truncation
  • Be aware that this function truncates at character boundaries, not word boundaries - consider implementing word-aware truncation for better readability if needed
  • For multi-byte character encodings (like emoji or certain Unicode), the function counts characters correctly but may still split multi-byte sequences
  • When displaying truncated text in UI, consider providing a way for users to view the full text (tooltip, expand button, etc.)
  • If max_length is less than or equal to the suffix length, the result will be just the suffix or potentially empty/malformed

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_summary 43.5% similar

    Creates a text summary using OpenAI's GPT models or returns a truncated version as fallback when API key is unavailable.

    From: /tf/active/vicechatdev/chromadb-cleanup/src/summarization/summarizer.py
  • function hash_text 40.2% similar

    Creates a SHA-256 hash of normalized text content to generate a unique identifier for documents, enabling duplicate detection and content comparison.

    From: /tf/active/vicechatdev/chromadb-cleanup/src/utils/hash_utils.py
  • function handle_potential_truncation 37.1% similar

    Detects and handles truncated meeting minutes by comparing agenda items to discussion sections, then attempts regeneration with enhanced instructions to ensure completeness.

    From: /tf/active/vicechatdev/leexi/app.py
  • function clean_text 33.8% similar

    Cleans and normalizes text content by removing HTML tags, normalizing whitespace, and stripping markdown formatting elements.

    From: /tf/active/vicechatdev/improved_convert_disclosures_to_table.py
  • function capitalize_unicode_name 32.3% similar

    Transforms Unicode character name strings by removing the word 'capital' and capitalizing the following word, converting strings like 'capital delta' to 'Delta'.

    From: /tf/active/vicechatdev/patches/util.py
← Back to Browse