views:

293

answers:

5

How to truncate the string to 75 characters only in Python?

This is how it was done in JavaScript:

var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
var info = (data.length > 75) ? data.substring[0,75] + '..' : data;
+6  A: 
info = (data[:75] + '..') if len(data) > 75 else data
Marcelo Cantos
+3  A: 

You could use this one-liner:

data = (data[:75] + '..') if len(data) > 75 else data
phoenix24
+2  A: 
"%s.." % data[:75] if len(data) > 75 else data

Slicing syntax is described in python manual. Study the manual contents and apply self-help to answer yourself on trivial operations like retrieving a substring.

Cheery
+2  A: 

Even more concise:

data = data[:75]

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

neil
Presumably he wants an ellipsis appended if the string is truncated.
FogleBird
You're right - I never noticed that. I can't think of a better way to do that than other answers.
neil
+4  A: 

Even shorter :

info = data[:75] + (data[75:] and '..')
stanlekub
Funny approach to do it. Though it's still a composite one-liner. ^^
Cheery