def trunc ( obj , max , left = 0 ) : s = str ( obj ) s = s . replace ( '\n' , '|' ) if len ( s ) > max : if left : return '...' + s [ len ( s ) - max + 3 : ] else : return s [ : ( max - 3 ) ] + '...' else : return s
python, truncating a string by length
Convert obj to string eliminate newlines and truncate the string to max characters . If there are more characters in the string add ... to the string . With left = True the string can be truncated at the beginning .
def trunc(obj, max, left=0):
    """
    Convert `obj` to string, eliminate newlines and truncate the string to `max`
    characters. If there are more characters in the string add ``...`` to the
    string. With `left=True`, the string can be truncated at the beginning.

    @note: Does not catch exceptions when converting `obj` to string with `str`.

    >>> trunc('This is a long text.', 8)
    This ...
    >>> trunc('This is a long text.', 8, left)
    ...text.
    """
    s = str(obj)
    s = s.replace('\n', '|')
    if len(s) > max:
        if left:
            return '...'+s[len(s)-max+3:]
        else:
            return s[:(max-3)]+'...'
    else:
        return s