Source

snippy / snippy.py

def snip(text, length=80, postfix='...'):
    """Snip a string to a length, while keeping it pretty.
    
    Snip requires the 'text' parameter, which is the string to be snipped.
    
    Snip accepts a 'length' parameter.  The resulting string is guaranteed
    to fit within that many characters.  The default is 80.
    
    Snip also accepts a 'postfix' parameter.  This is what will be
    appended if the string needs to be shortened.  The default is '...'
    
    >>> snip("The quick brown fox jumps over the lazy dog.", length=20)
    'The quick brown f...'
    >>> snip("The quick brown fox jumps over the lazy dog.", length=20, postfix='--more')
    'The quick brow--more'
    >>> snip("Small enough strings are untouched.")
    'Small enough strings are untouched.'
    """
    
    if len(text) < length:
        return text
    elif len(postfix) >= length:
        return postfix[:length]
    else:
        return text[:length-len(postfix)] + postfix