The Python Oracle

Python truncate a long string

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon

--

Chapters
00:00 Python Truncate A Long String
00:21 Accepted Answer Score 604
00:39 Answer 2 Score 201
00:51 Answer 3 Score 165
00:59 Answer 4 Score 49
01:18 Thank you

--

Full question
https://stackoverflow.com/questions/2872...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 604


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

This code matches the JavaScript, but you should consider using data[:73] so that the total result including the .. fits in 75 characters.




ANSWER 2

Score 201


Even more concise:

data = data[:75]

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




ANSWER 3

Score 165


Even shorter :

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



ANSWER 4

Score 49


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