Python truncate a long string

StackOverflow

How does one truncate a string to 75 characters in Python?

This is how it is done in JavaScript:

var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
var info = (data.length > 75) ? data.substring[0,75] + ".." : data;

Answer rating: 498

info = (data[:75] + "..") if len(data) > 75 else data

Answer rating: 141

Even shorter :

info = data[:75] + (data[75:] and "..")

Answer rating: 104

If you are using Python 3.4+, you can use textwrap.shorten from the standard library:

Collapse and truncate the given text to fit in the given width.

First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is returned. Otherwise, enough words are dropped from the end so that the remaining words plus the placeholder fit within width:

>>> textwrap.shorten("Hello  world!", width=12)
"Hello world!"
>>> textwrap.shorten("Hello  world!", width=11)
"Hello [...]"
>>> textwrap.shorten("Hello world", width=10, placeholder="...")
"Hello..."




Get Solution for free from DataCamp guru