def smart_truncate(string, max_length=0, word_boundaries=False, separator=' '):
 string = string.strip(separator)
 if (not max_length):
  return string
 if (len(string) < max_length):
  return string
 if (not word_boundaries):
  return string[:max_length].strip(separator)
 if (separator not in string):
  return string[:max_length]
 truncated = ''
 for word in string.split(separator):
  if word:
   next_len = ((len(truncated) + len(word)) + len(separator))
   if (next_len <= max_length):
    truncated += '{0}{1}'.format(word, separator)
 if (not truncated):
  truncated = string[:max_length]
 return truncated.strip(separator)

def smart_truncate ( string , max_length = 0 , word_boundaries = False , separator = ' ' ) : string = string . strip ( separator ) if ( not max_length ) : return string if ( len ( string ) < max_length ) : return string if ( not word_boundaries ) : return string [ : max_length ] . strip ( separator ) if ( separator not in string ) : return string [ : max_length ] truncated = '' for word in string . split ( separator ) : if word : next_len = ( ( len ( truncated ) + len ( word ) ) + len ( separator ) ) if ( next_len <= max_length ) : truncated += '{0}{1}' . format ( word , separator ) if ( not truncated ) : truncated = string [ : max_length ] return truncated . strip ( separator )
truncate a string .