The Python Oracle

Python truncate a long string

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Question
00:27 Accepted answer (Score 567)
00:37 Answer 2 (Score 178)
00:54 Answer 3 (Score 157)
01:06 Answer 4 (Score 137)
01:48 Thank you

--

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

Answer 3 links:
[textwrap.shorten]: https://docs.python.org/3.4/library/text...

--

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