def shorten(string, max_length=80, trailing_chars=3):
''' trims the 'string' argument down to 'max_length' to make previews to long string values '''
assert type(string).__name__ in {'str', 'unicode'}, 'shorten needs string to be a string, not {}'.format(type(string))
assert type(max_length) == int, 'shorten needs max_length to be an int, not {}'.format(type(max_length))
assert type(trailing_chars) == int, 'shorten needs trailing_chars to be an int, not {}'.format(type(trailing_chars))
assert max_length > 0, 'shorten needs max_length to be positive, not {}'.format(max_length)
assert trailing_chars >= 0, 'shorten needs trailing_chars to be greater than or equal to 0, not {}'.format(trailing_chars)
return (
string
) if len(string) <= max_length else (
'{before:}...{after:}'.format(
before=string[:max_length-(trailing_chars+3)],
after=string[-trailing_chars:] if trailing_chars>0 else ''
)
)
if __name__ == '__main__':
test_long_string = str([i for i in range(40)])
print(test_long_string)
print(shorten(test_long_string))
print(shorten(test_long_string, trailing_chars=0))