string truncation
Python programming
text manipulation
string handling
Python tips

Python truncate a long string

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

String truncation in Python looks simple at first, but production code usually needs more than plain slicing. You may need to preserve word boundaries, add an ellipsis, keep filenames readable, or normalize text for logs. A good truncation helper should make these rules explicit so different parts of your application behave consistently.

Start With A Clear Policy

Before choosing implementation, define what truncation means for your use case.

  • Is the limit by characters, words, or bytes.
  • Should an ellipsis be added.
  • Should output preserve whole words.
  • Should internal whitespace be collapsed.
  • Should beginning and end both remain visible.

Without policy, teams often implement inconsistent truncation in templates, API handlers, and logging utilities.

Basic Character Truncation

For fixed character caps, slicing is still the fastest baseline.

python
1def truncate_chars(text: str, max_len: int) -> str:
2    if max_len < 0:
3        raise ValueError("max_len must be non-negative")
4    return text[:max_len]
5
6print(truncate_chars("The quick brown fox", 10))

This is deterministic, but it can cut words in awkward places.

Add Ellipsis Safely

Most user interfaces should indicate that text was shortened.

python
1def truncate_with_ellipsis(text: str, max_len: int, suffix: str = "...") -> str:
2    if max_len < 0:
3        raise ValueError("max_len must be non-negative")
4    if len(text) <= max_len:
5        return text
6    if max_len <= len(suffix):
7        return text[:max_len]
8    return text[: max_len - len(suffix)] + suffix
9
10print(truncate_with_ellipsis("A very long sentence", 12))

This helper avoids returning a string longer than the requested limit.

Word Boundary Truncation

If readability matters, cut at the last full word within the cap.

python
1def truncate_words(text: str, max_len: int, suffix: str = "...") -> str:
2    if len(text) <= max_len:
3        return text
4
5    room = max_len - len(suffix)
6    if room <= 0:
7        return text[:max_len]
8
9    chunk = text[:room]
10    if " " in chunk:
11        chunk = chunk.rsplit(" ", 1)[0]
12    return chunk + suffix
13
14print(truncate_words("The quick brown fox jumps over", 18))

This gives cleaner previews for article cards and notification text.

Standard Library Option

textwrap.shorten is convenient for word aware truncation.

python
1import textwrap
2
3text = "The quick brown fox jumps over the lazy dog"
4print(textwrap.shorten(text, width=20, placeholder="..."))

It collapses repeated whitespace before truncating, which is often useful for user submitted text.

Middle Truncation For Paths And IDs

For file paths or hashes, start and end are often more important than the middle.

python
1def middle_truncate(text: str, max_len: int, marker: str = "...") -> str:
2    if len(text) <= max_len:
3        return text
4    if max_len <= len(marker) + 2:
5        return text[:max_len]
6
7    keep_each_side = (max_len - len(marker)) // 2
8    left = text[:keep_each_side]
9    right = text[-(max_len - len(marker) - keep_each_side):]
10    return left + marker + right
11
12print(middle_truncate("/srv/releases/2026-03-01/build/output/report.json", 24))

This is common in developer tools and admin consoles.

Truncation For Logging

Logs should stay one line and avoid huge payloads.

python
1def truncate_for_log(text: str, max_len: int) -> str:
2    compact = " ".join(text.split())
3    return truncate_with_ellipsis(compact, max_len)
4
5sample = "Request failed:\nline one details\tline two details"
6print(truncate_for_log(sample, 36))

Normalizing whitespace before truncation improves log parsing and search.

Unicode Considerations

Python slicing operates on code points, not visual grapheme clusters. For most English text this is fine. For complex scripts and emoji sequences, a visual character can contain multiple code points, so apparent length may differ from len(text).

If precise visual truncation is required, use a dedicated Unicode aware library and test with multilingual samples.

Common Pitfalls

  • Truncating without an indicator and confusing users.
  • Using one truncation style for every context.
  • Forgetting to validate very small limits when adding suffixes.
  • Truncating identifiers used for business logic instead of presentation only.
  • Ignoring Unicode display behavior in multilingual interfaces.

Summary

  • Start truncation work by defining policy, not by writing slices everywhere.
  • Use plain slicing for strict fixed limits and internal processing.
  • Add ellipsis and word boundary behavior for user facing text.
  • Use middle truncation when start and end carry most meaning.
  • Centralize helpers so UI, APIs, and logs apply consistent rules.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.