How to Truncate a String to a Specific Length in Python?

In this tutorial, I will explain how to truncate a string to a specific length in Python. As a Python developer based in the USA, working on a web application project for one of my clients in New York, I came across a scenario where I needed to display user names and process text for analysis then, I explored more about this topic and I will share my findings in this article.

String Truncation in Python

String truncation involves shortening a string to a specified number of characters. This is particularly useful when you want to ensure that text fits within a certain display area or when you need to limit input data, such as usernames or comments. For example, if you’re developing a social media application, you might want to limit user bios to 150 characters.

Read How to Get the Last 4 Characters of a String in Python?

Truncate a String to a Specific Length in Python

Python provides several ways to accomplish this task. Let us see some important methods.

1. Use Slicing

Python provides a simple way to truncate strings using slicing. Slicing allows you to extract a portion of a string based on specified indices.

Example 1: Simple Slicing

Let’s say we have a user name, “Christopher Johnson”, and we want to truncate it to the first 10 characters:

user_name = "Christopher Johnson"
truncated_name = user_name[:11]  
print(truncated_name)

Output:

Christopher

I have executed the above example code and added the screenshot below.

Truncate a String to a Specific Length in Python

In this example, user_name[:10] returns the substring from the start of the string up to (but not including) the 10th character.

Read How to Get the Last 3 Characters of a String in Python?

Example 2: Add Ellipsis

In some cases, you may want to indicate that the string has been truncated by adding an ellipsis (“…”). Here’s how you can do that:

def truncate_string(s, length):
    if len(s) > length:
        return s[:length-3] + '...'  # Subtract 3 for the ellipsis
    return s

user_bio = "I love hiking, reading, and exploring new places."
truncated_bio = truncate_string(user_bio, 30)
print(truncated_bio) 

Output:

I love hiking, reading, and...

I have executed the above example code and added the screenshot below.

How to Truncate a String to a Specific Length in Python

In this function, if the string exceeds the specified length, we slice it and add an ellipsis to indicate truncation.

Read How to Check if a Word is in a String in Python?

Truncate Strings to Fit Specific Widths

When dealing with user input or displaying text in a UI, you might want to truncate based on specific widths rather than character counts. This requires a slightly different approach.

Example 3: Word-Based Truncation

Suppose you want to truncate a sentence without cutting off words. You can achieve this by splitting the string into words and then joining them back together until you reach the desired length.

def truncate_to_width(s, width):
    words = s.split()
    truncated = ''
    for word in words:
        if len(truncated) + len(word) + 1 <= width:
            truncated += word + ' '
        else:
            break
    return truncated.strip() + '...' if len(truncated) > 0 else ''

description = "John Doe is a software engineer who enjoys building applications."
truncated_description = truncate_to_width(description, 40)
print(truncated_description) 

Output:

John Doe is a software engineer who...

I have executed the above example code and added the screenshot below.

Truncate a String to a Specific Length in Python word based

This function constructs a new string by adding words until it reaches the specified width, ensuring that no words are cut off.

Read How to Shuffle Characters in a String using Python?

Handle Special Cases: Strings with HTML

When working with HTML content, you may need to truncate strings while preserving the HTML structure. This can be a bit tricky but is manageable with Python’s built-in libraries.

Example 4: Truncate HTML Content

Using the BeautifulSoup library can help you handle HTML safely while truncating:

from bs4 import BeautifulSoup

def truncate_html(html, length):
    soup = BeautifulSoup(html, 'html.parser')
    text = soup.get_text()
    return truncate_string(text, length)

html_content = "<p>John Smith is a passionate developer.</p>"
truncated_html = truncate_html(html_content, 20)
print(truncated_html) 

Output:

John Smith is a...

In this example, we first extract the text from the HTML and then apply our truncation logic.

Read How to Check if a String is a Valid UUID in Python?

Conclusion

In this tutorial, I have explained how to truncate a string to a specific length in Python. I discussed methods like slicing , and truncating strings to fit specific widths with examples. I also discussed how to handle special cases that is a string with HTML.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.