Python truncate a long string
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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.
This is deterministic, but it can cut words in awkward places.
Add Ellipsis Safely
Most user interfaces should indicate that text was shortened.
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.
This gives cleaner previews for article cards and notification text.
Standard Library Option
textwrap.shorten is convenient for word aware truncation.
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.
This is common in developer tools and admin consoles.
Truncation For Logging
Logs should stay one line and avoid huge payloads.
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
- Python try...except comma vs 'as' in except
- python tsne.transform does not exist?
- Python tutorial code from RabbitMQ failing to run
- Python Twisted dynamic protocols for sending packets at runtime
- Python Twisted wait for a variable to be filled by another event
- python type hint - can tensorflow data type be used?
- Python type hinting without cyclic imports
- Python type inference for autocompletion
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.