🛠️ToolsShed

文本截断工具

使用可自定义省略号将文本截断到指定字符数或单词数。

常见问题

代码实现

def truncate_chars(text: str, max_chars: int, ellipsis: str = "...") -> str:
    """Truncate text to max_chars characters."""
    if len(text) <= max_chars:
        return text
    return text[:max_chars - len(ellipsis)] + ellipsis


def truncate_words(text: str, max_words: int, ellipsis: str = "...") -> str:
    """Truncate text to max_words words."""
    words = text.split()
    if len(words) <= max_words:
        return text
    return " ".join(words[:max_words]) + ellipsis


# Examples
text = "The quick brown fox jumps over the lazy dog"

print(truncate_chars(text, 20))        # "The quick brown fo..."
print(truncate_words(text, 5))         # "The quick brown fox jumps..."
print(truncate_chars(text, 20, " …")) # "The quick brown f …"

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.