Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #12108
| References | <a24faeb6-ebe4-41bf-8c20-9cd46547a3bd@b14g2000vbg.googlegroups.com> |
|---|---|
| Date | 2011-08-23 10:27 -0700 |
| Subject | Re: truncating strings |
| From | Chris Rebert <clp2@rebertia.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.362.1314120465.27778.python-list@python.org> (permalink) |
On Tue, Aug 23, 2011 at 9:29 AM, Roy Smith <roy@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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
truncating strings Roy Smith <roy@panix.com> - 2011-08-23 09:29 -0700
Re: truncating strings Chris Rebert <clp2@rebertia.com> - 2011-08-23 10:27 -0700
Re: truncating strings Seebs <usenet-nospam@seebs.net> - 2011-08-23 20:52 +0000
Re: truncating strings Ethan Furman <ethan@stoneleaf.us> - 2011-08-23 15:02 -0700
Re: truncating strings Seebs <usenet-nospam@seebs.net> - 2011-08-23 22:00 +0000
Re: truncating strings Ethan Furman <ethan@stoneleaf.us> - 2011-08-23 16:44 -0700
Re: truncating strings Seebs <usenet-nospam@seebs.net> - 2011-08-24 04:21 +0000
Re: truncating strings Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-24 11:24 +1000
csiph-web