Truncate String to Given Length and Add Ellipsis if Necessary using Python

Custom implementation

def truncate_string(str_input, max_length):
    str_end = '...'
    length = len(str_input)
    if length > max_length:
        return str_input[:max_length - len(str_end)] + str_end

    return str_input


text = 'Hello world'
print(truncate_string(text, 10))  # Hello w...
print(truncate_string(text, 11))  # Hello world

Leave a Comment

Cancel reply

Your email address will not be published.