pythontruncate

Python truncate a long string


How does one truncate a string to 75 characters in Python?

This is how it is done in JavaScript:

const data = "saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";
const info = (data.length > 75) ? data.substring(0, 75) + '..' : data;
console.log(info);


Solution

  • 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.