Python truncate a long string


Question

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;
1
197
7/18/2016 9:03:19 PM

Accepted Answer

info = (data[:75] + '..') if len(data) > 75 else data
351
5/20/2010 9:38:05 AM

Even shorter :

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon