Skip to content

Instantly share code, notes, and snippets.

@adamjforster
Created January 26, 2011 15:07
Show Gist options
  • Save adamjforster/796797 to your computer and use it in GitHub Desktop.
Save adamjforster/796797 to your computer and use it in GitHub Desktop.
Truncate a string at the nearest delimiter to a certain length.
def truncate_on(string, length, delimiter=' '):
"""Truncate a string at the nearest delimiter to a certain length."""
length = int(length)
if len(string) > length:
index = string.rfind(delimiter, 0, length)
if index == -1:
string = string[:50]
else:
string = string[:index]
return string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment