truncating strings

Chris Rebert clp2 at rebertia.com
Tue Aug 23 19:27:42 CEST 2011


On Tue, Aug 23, 2011 at 9:29 AM, Roy Smith <roy at panix.com> wrote:
> I want to log a string but only the first bunch of it, and add "..."
> to the end if it got truncated.  This certainly works:
>
>          log_message = message
>          if len(log_message) >= 50:
>            log_message = log_message[:50] + '...'
>          logger.error("FAILED: '%s', '%s', %s, %s" % (log_message,
> route, params, e.code))
>
> but it bugs me that there should be some cleaner way to do this.  I'm
> fantasizing about something along the lines of:
>
>          logger.error("FAILED: '%s{50}', '%s', %s, %s" % (message,
> route, params, e.code))
>
> does anything like this exist?

You can specify a maximum width to truncate the string to, but I don't
see any built-in way to add an elision indication (e.g. "...").

>>> "%.4s" % "spam and eggs"
'spam'
>>> "{:.4s}".format("spam and eggs")
'spam'

You could define something to wrap strings and override __format__()
or similar, but that seems like overkill.

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list