python 缩短python中的长字符串,这样东西就不会泛滥

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 缩短python中的长字符串,这样东西就不会泛滥相关的知识,希望对你有一定的参考价值。

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))

以上是关于python 缩短python中的长字符串,这样东西就不会泛滥的主要内容,如果未能解决你的问题,请参考以下文章