12

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"

2 Answers 2

21
def cap(s, l):
    return s if len(s)<=l else s[0:l-3]+'...'
Sign up to request clarification or add additional context in comments.

1 Comment

I'll take that as a no to it being in the standard library. Thanks for the function :)
1

Probably the most flexibile (short of just slicing) way is to create a wrapper around textwrap.wrap such as: (bear in mind though, it does try to be smart about splitting in some places which may not get exactly the result you're after - but it's a handy module to know about)

def mywrap(string, length, fill=' ...'):
    from textwrap import wrap
    return [s + fill for s in wrap(string, length - len(fill))]

s = "Hello, world! I'm a string"
print mywrap(s, 10)
# ['Hello, ...', 'world! ...', "I'm a ...", 'string ...']

Then just take the elements you're after.

1 Comment

Compared to your example, textwrap.shorten might be more applicable here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.