Programming & Development / April 19, 2025

Smart Notification Shortening in Python with Character Limits

truncate message python notification shortening algorithm python string crop whole words add ellipsis to message message display with limit python smart text cropping python python notification preview

πŸ”” Prepare Notification Message with Length Limit in Python

πŸ“‹ Problem Overview

You're building a notification system where messages are shown on a mobile screen. The message must not exceed K characters, and it must be cropped properly if it’s too long β€” meaning only whole words are kept, and an ellipsis ("...") is added when cropping occurs.

✨ Cropping Rules

Given:

  • message: a space-separated string.
  • K: the character limit for the notification.

Produce:

  • A string of at most K characters that:
  • Ends with " ..." if cropped (note: a space before the three dots).
  • Is as long as possible without breaking words.
  • If the whole message fits, return it as is.
  • If no word fits, return only "..." (3 dots, no space before).

βœ… Examples

MessageKOutput"And now here is my secret"15"And now ...""There is an animal with four legs"15"There is an ...""super dog"4"...""how are you"20"how are you"

🧠 Algorithm Breakdown

  1. Check edge case: If K < 3, return "..." right away.
  2. Split the message into words.
  3. Build the message one word at a time, stopping when adding another word would exceed the limit.
  4. If cropping was necessary, check if there's room for " ..." and add it properly.
  5. If no word fits, return only "...".

πŸ§‘β€πŸ’» Python Implementation

python

def solution(message, K):
    if K < 3:
        return "..."

    words = message.split()
    notification = ""
    
    for word in words:
        if notification:
            # Check space + word
            if len(notification) + len(word) + 1 <= K:
                notification += " " + word
            else:
                break
        else:
            # First word (no leading space)
            if len(word) <= K:
                notification = word
            else:
                break

    # Full message fits
    if len(notification) == len(message):
        return notification

    # If no words fit
    if not notification:
        return "..."

    # Ensure we can add " ..."
    if len(notification) + 4 <= K:
        return notification + " ..."
    else:
        # Edge case: crop an extra word if needed to fit the ellipsis
        words = notification.split()
        trimmed = ""
        for word in words[:-1]:
            if not trimmed:
                test = word
            else:
                test = trimmed + " " + word
            if len(test) + 4 <= K:
                trimmed = test
            else:
                break
        return trimmed + " ..." if trimmed else "..."

πŸ“Œ Important Notes

  • " ..." is 4 characters including the space.
  • The logic handles the corner case where no word fits within the limit.
  • This is a greedy solution β€” it adds as many full words as possible from the beginning.

πŸ§ͺ Test It!

python

print(solution("And now here is my secret", 15))         # "And now ..."
print(solution("There is an animal with four legs", 15)) # "There is an ..."
print(solution("super dog", 4))                          # "..."
print(solution("how are you", 20))                       # "how are you"



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex