Python truncate a long string
Here's a Python Lambda function to truncate a string to a maximum length n
and append an ellipsis if it exceeds that length:
Let's test it with the string "Sample text for truncation" and a maximum length of 10:
The output will be:
Sample te...
Ensuring the output doesn't exceed n
characters, including the ellipsis.
Express truncation in Python
Truncating a string is a common need, especially for fitting long text within a specific user interface space. We typically append an ellipsis to indicate content omission. Here are few ways to approach it in Python:
One-liner solution
A handy one-liner solution uses a lambda function for brevity. Truncated text is capped with an ellipsis, only if it was really truncated; otherwise, the original text is returned as it is short enough.
Creating a reusable function
A reusable function is a best practice for maintainable code. It takes text, limit, and an optional flag to indicate whether to append an ellipsis.
Using Python's textwrap module
Python's standard textwrap module has a shorten()
function:
This function smartly breaks on spaces and adds the placeholder, preventing word splitting when truncating.
Advanced truncation tactics
For specific scenarios or more control, consider these advanced string truncation techniques.
Django truncation
In a Django environment, the Truncator
class from the utility django.utils.text
comes handy:
Studying existing solutions
Digging into how popular libraries, like Django's Truncator
, implement truncation can offer valuable insights into handling complex scenarios.
Edge case handling
Be prepared for the unexpected: long strings
, empty strings
, or whitespace-heavy strings
. Make sure your function handles these.
Including ellipsis in the limit
If the limit should include the ellipsis length, adjust the slice or limit as necessary.
Customization tweaks
Customizations you can consider for enhanced readability and precision.
Ellipsis indication
An ellipsis (...
) at the end is a universal indication of truncation. Always remember this!
Concise conditional truncation
A concise conditional can be achieved with the and
operator:
Equivalent in JavaScript
For those switching over from JavaScript, Python slicing
is a direct equivalent of JavaScript's substring()
function.
Handling Unicode
Stay aware of Unicode characters. A single visual character can have multiple code points.
Was this article helpful?