Python function for capping a string to a maximum length

python, string

Solution

def cap(s, l):
    return s if len(s)<=l else s[0:l-3]+'...'

Problem

Is there a function in Python, built-in or in the standard library, for capping a string to a certain length, and if the length was exceeded, append three dots (...) after it? For example: ``` >>> hypothetical_cap_function("Hello, world! I'm a string", 10) "Hello, ..." >>> hypothetical_cap_function("Hello, world! I'm a string", 20) "Hello, world! I'm..." >>> hypothetical_cap_function("Hello, world! I'm a string", 50) "Hello, world! I'm a string" ```

Original source