Python truncate a long string

ID : 10422

viewed : 31

Tags : pythonpython

Top 5 Answer for Python truncate a long string

vote vote


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


Even shorter :

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


Even more concise:

data = data[:75] 

If it is less than 75 characters there will be no change.

vote vote


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...' 
vote vote


For a Django solution (which has not been mentioned in the question):

from django.utils.text import Truncator value = Truncator(value).chars(75) 

Have a look at Truncator's source code to appreciate the problem:

Concerning truncation with Django: Django HTML truncation

Top 3 video Explaining Python truncate a long string