truncating strings

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Aug 23 21:24:14 EDT 2011


Seebs wrote:

> Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
> [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> print "%.5s" % ("hello there, truncate me!")
> hello


Well, whadda you know, I learned something new :)


In any case, this doesn't solve the OP's problem, as he wants to truncate
the input string, and append '...' if and only if it were truncated.

The right solution is to wrap the functionality in a function. It's not
hard, and is elegant. Not everything needs to be a built-in.

# Untested.
def truncate(s, maxwidth=50):
    if len(s) <= maxwidth:
        return s
    s = s[:maxwidth - 3]
    return s + '...'



-- 
Steven




More information about the Python-list mailing list