Python function for capping a string to a maximum length

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"

Answers


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

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.


Need Your Help

How to calculate TF*IDF for a single new document to be classified?

machine-learning classification information-retrieval text-mining document-classification

I am using document-term vectors to represent a collection of document. I use TF*IDF to calculate the term weight for each document vector. Then I could use this matrix to train a model for document

SQL function return-type: TABLE vs SETOF records

sql postgresql return-type sql-function sql-types

What's the difference between a function that returns TABLE vs SETOF records, all else equal.