Python truncate a long string

ID : 10422

viewed : 24

Tags : pythonpython

Top 5 Answer for Python truncate a long string

vote vote

90

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

85

Even shorter :

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

74

Even more concise:

data = data[:75] 

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

vote vote

69

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

60

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: https://github.com/django/django/blob/master/django/utils/text.py#L66

Concerning truncation with Django: Django HTML truncation

Top 3 video Explaining Python truncate a long string

Related QUESTION?