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.
Collected python utilities
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment