Skip to content

Instantly share code, notes, and snippets.

@agonzalezro
Created April 13, 2012 09:43
Show Gist options
  • Save agonzalezro/2375458 to your computer and use it in GitHub Desktop.
Save agonzalezro/2375458 to your computer and use it in GitHub Desktop.
Create a "summary" with ellipsis from a big string
def truncate(message, size, suffix='...'):
'''Create message cutted with ellipses.
>>> message = 'hello crazy world'
>>> truncate(message, 1)
''
>>> truncate(message, 9)
'hello...'
>>> truncate(message, 15)
'hello crazy...'
>>> truncate(message, 128)
'hello crazy world'
'''
#max_size -= 1 # Count the index 0
if len(message) >= size:
rindex = size - len(suffix)
if rindex > 0:
message = message[:rindex]
message = message[:message.rfind(' ')]
message += suffix
else:
message = ''
return message[:size]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment