Explain Codes LogoExplain Codes Logo

Python truncate a long string

python
functions
best-practices
dataframe
Anton ShumikhinbyAnton Shumikhin·Oct 8, 2024
TLDR

Here's a Python Lambda function to truncate a string to a maximum length n and append an ellipsis if it exceeds that length:

trunc_str = (lambda s, n: s[:n] + '...' if len(s) > n else s)

Let's test it with the string "Sample text for truncation" and a maximum length of 10:

print(trunc_str("Sample text for truncation", 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.

truncate = lambda text, limit: text if len(text) <= limit else text[:limit - 3] + '...' # Great example of how Python rewards laziness!

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.

def truncate(text, limit, ellipsis=True): return text if len(text) <= limit else text[:limit - 3] + ('...' if ellipsis else '') # Worried about long texts? Tuple this function up with your texts, problem solved!

Using Python's textwrap module

Python's standard textwrap module has a shorten() function:

import textwrap print(textwrap.shorten("Long text to be truncated", width=75, placeholder='...')) # Short and sweet, just like this piece of code!

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:

from django.utils.text import Truncator print(Truncator("Sample text for truncation").chars(75)) # The secret weapon for Django developers against long texts!

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:

truncated = data and data[:75] + '...' if len(data) > 75 else data # Because keeping it short and simple never hurt anyone!

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.