[Python-Dev] Replacement for print in Python 3.0

Nick Coghlan ncoghlan at gmail.com
Thu Sep 8 15:15:54 CEST 2005


Barry Warsaw wrote:
> On Wed, 2005-09-07 at 08:55, Nick Coghlan wrote:
> 
> 
>>The leading 'p' (for 'positional') is necessary to get around the fact that $1 
>>is currently an illegal identifier in a Template
> 
> 
> That should be fixable. Ideally, $1 is better than $p1.

Oh, I know. I just didn't feel like cranking my brain up to the point of 
figuring out the necessary change to the string.Template regex. It turns out 
the one required change to the pattern is truly trivial though (I guess the 
grief we gave PEP 292 about easy customisation was actually worthwhile):

from string import Template
class fmtTemplate(Template):
     idpattern = '[_a-z0-9]*'

def format(*args, **kwds):
     if kwds and (len(args) > 1):
         raise ValueError("Cannot use both keyword and positional arguments")
     fmt = fmtTemplate(args[0])
     kwds.update(((str(idx), arg) for idx, arg in enumerate(args)))
     return fmt.substitute(**kwds)

Py> format("$1: $2", "Num bees", 0.5)
'Num bees: 0.5'


Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.blogspot.com


More information about the Python-Dev mailing list