[Python-3000] String formating operations in python 3k

Adam DePrince adam.deprince at gmail.com
Mon Apr 3 04:42:20 CEST 2006


On Sun, 2006-04-02 at 22:27 +0200, Georg Brandl wrote:
> Crutcher Dunnavant wrote:
> > Python currently supports  'S % X', where S is a strinng, and X is one of:
> > * a sequence
> > * a map
> > * treated as (X,)
> > 
> > But I have some questions about this for python 3000.
> > 
> > 1. Shouldn't there be a format method, like S.format(), or S.fmt()?
> 
> Possible, but why? "%" works quite fine. "Abusing" the modulus operator
> is okay in this context since the symbol gives a nonoverseeable clue to
> what the construct is doing.
> 
> > 2. What about using __call__ instead of / in addition to __rmod__?
> > * "time: %s"(time.ctime()) == "time: %s" % time.ctime()
> > * "%(a)s %(b)s"(a=1, b=2) == "%(a)s %(b)s" % {'a'=1, 'b'=2}
> Damn ugly. How would you explain to a newbie that you can _call_ a string?

Carefully.  You can't predict how a "newbie" might react to a language
feature.  Even now from a distance of some 7 years I recall with
fondness my first taste of Python.  My thoughts were somewhat along the
lines of:

"""What an odd use of %.  Its as if the string is an expression in some
quaint language and we are evaluating it.  I would think / and % would
better mean:

"string"/n == "string"[::n]

"string"%m == \
lambda s,n:[s[k*n:(k+1)*n] for k in range( 0, len( s)/n,n )]"""

Of course my transcription of the semantics would have differed somewhat
at the time.

IIRC, the motivation for the use of dict instead of dictionary was based
on a two pronged test that I propose we henceforth call the "dictionary
test."  dict was selected over dictionary because the full form was
harder to spell than the abbreviation was to pronounce.

Format/fmt doesn't pass that, therefore I'd recommend sticking
to .format.  

Thinking back, lambda x:"somestring"%( x,) was a common pattern until
list interpolation made ["somestring"%( x, ) for x ] the more common
form, so the need for a callable form is somewhat reduced.  

As nice as that would be, are there better uses for a callable string?
Eval perhaps?

S % X where X is a sequence or dict is obviously necessary, but I've
always thought that the automatic rewriting of a non-sequence X as (X,)
to be a bit of syntactic saccharine.  

1. The single parameter version breaks when a tuple is the single
object.

2. Only tuples are accepted; S % X doesn't work with other data-types.
I could say tuple( my-sequence ).  

Deprecate the string_mod operation and replace it with .format.  This
would eliminate yet another obscure method of parameter passing.   It
would also give map users a real callable they could use:
"mystring".format 


Cheers - Adam






More information about the Python-3000 mailing list