[Python-3000] String formating operations in python 3k
Nick Coghlan
ncoghlan at gmail.com
Sun Apr 2 23:56:39 CEST 2006
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.
A "format" function that accepted the pattern as the first argument and the
values to be interpolated as the remaining arguments would be even clearer
though. Instead of giving you a clue, it would tell you exactly what's going on.
Basing this on string.Template gives very readable syntax when using
positional arguments, as well as allowing each positional argument to be used
more than once:
>>> x = 3
>>> format("$1 * $1 = $2", x, x*x)
'3 * 3 = 9'
Tweaking the string.Template regex a bit even allows formatting:
>>> x = 3.14159
>>> format("$[.2f]1 * $[.2f]1 = $[.4f]2", x, x*x)
'3.14 * 3.14 = 9.8696'
>> 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?
> And that _calling_ a string does a formatting operation?
> For me, string formatting with "%" is fine as it is.
I think there is merit in having a higher level interpolation syntax
underpinned by the raw mod-formatting syntax.
> BTW, has anyone seen string.Template being used somewhere?
I imagine Barry, at least, (and probably others) are using it for its primary
intended use case - localisation. As more applications move to requiring 2.4,
then its use is also likely to increase.
Cheers,
Nick.
[1] http://mail.python.org/pipermail/python-dev/2005-September/056231.html
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://www.boredomandlaziness.org
More information about the Python-3000
mailing list