Skip to content

Instantly share code, notes, and snippets.

@xiconet
Last active May 8, 2017 15:44
Show Gist options
  • Save xiconet/c3f39d6eabf6f910961206806f7dd9ae to your computer and use it in GitHub Desktop.
Save xiconet/c3f39d6eabf6f910961206806f7dd9ae to your computer and use it in GitHub Desktop.

Revisions

  1. xiconet revised this gist May 8, 2017. No changes.
  2. xiconet created this gist Apr 25, 2017.
    43 changes: 43 additions & 0 deletions utils.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    #!/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