VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-truncate-a-long-string-after-given-size-in-python/

⇱ How to Truncate a Long String after Given Size in Python? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Truncate a Long String after Given Size in Python?

Last Updated : 23 Jul, 2025

Truncating a long string to a specified size in Python can be achieved using several methods, such as slicing, string methods, and specialized libraries. Each approach is suitable for different scenarios based on your requirements. Let’s explore how to efficiently truncate strings.

Using String Slicing (Fixed-length truncation)

The simplest way to truncate a string is by using slicing ([:]). This method is fast and intuitive for fixed-size truncation.


Output
Welcome to

String slicing extracts the characters up to the specified index, making it ideal for quick truncation tasks.

If you want to indicate truncation, you can append an ellipsis (...) or other markers after slicing.

Let's look at another method to truncate a long string after given size in python:

Using textwrap.shorten for Whole-word truncation

The textwrap module provides a built-in shorten method that truncates a string intelligently, ensuring whole words are preserved.


Output
Welcome to...

The shorten method avoids breaking words by truncating to the nearest whole word and adding a placeholder if necessary.

Comment