#!/usr/bin/env python """Collect utilities here __VERSION: 0.1 __AUTHOR: xiconet """ MAXLEN = 60 START_AT = 2 def shorten(s, maxlen=MAXLEN): """Shorten a string while keeping its last two words""" words = s.split(" ") left_part = words[:-2] right_part = words[-2:] while len(s) > maxlen: left_part.pop() s = " ".join(left_part + ["..."] + right_part) return s def shorten_at(s, start_at=START_AT, maxlen=MAXLEN): """shorten a string at the chosen word position, counting from the LEFT end """ if len(s) == maxlen: return s words = s.split(" ") N = start_at if not 0 < N < len(words): print "error: start_at must be an integer N such as 0 < N < num(words in string)" return s lp = words[:-N] rp = words[-N:] while len(s) > maxlen: try: left_part.pop() except IndexError as err: print "error: unsuited start_at value: %s" % err return s s = " ".join(lp + ["..."] + rp) return s