[Python-Dev] *Simpler* string substitutions
Paul Prescod
paul@prescod.net
Thu, 20 Jun 2002 13:26:03 -0700
Gustavo Niemeyer wrote:
>
>...
>
> I'm curious.. where did you get this from? Have you counted?
No.
> I think 99% of the statistics are forged to enforce an opinion. :-)
I said it was based only on my experience!
> ... Think about these real examples, taken
> from *one* single module (BaseHTTPServer):
>
> "%s %s %s\r\n" % (self.protocol_version, str(code), message)
Let's presume a "sub" method with the features of Ping's string
interpolation PEP. This would look like:
"${self.protocol_version}, $code, $message\r\n".sub()
Shorter and simpler.
> "%s - - [%s] %s\n" % (self.address_string(),
> self.log_date_time_string(),
> format%args))
"${self.address_string()} - - [${self.log_date_time_string()}]
${format.sub(args)}".sub()
But I would probably clarify that:
addr = self.address_string()
time = self.log_date_time_string()
command = format.sub(args)
"$addr - - [$time] $command\n".sub()
> "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (self.weekdayname[wd],
> day,
> self.monthname[month], year,
> hh, mm, ss)
This one is part of the small percent that uses formatting codes. It
wouldn't be rocket science to integrate formatting codes with the "$"
notation $02d{day} but it would also be fine if this involved a call to
textutils.printf()
> "Serving HTTP on", sa[0], "port", sa[1], "..."
This doesn't use "%" to start with, but it is still clearer (IMO) in the
new notation:
"Serving HTTP on ${sa[0]} port ${sa[1]} ..."
> "Bad HTTP/0 .9 request type (%s)" % `command`
"Bad HTTP/0 .9 request type ${`command`}"
etc.
Paul Prescod