[Python-3000] String formating operations in python 3k
Ian Bicking
ianb at colorstudy.com
Mon Apr 3 18:13:28 CEST 2006
Barry Warsaw wrote:
> On Mon, 2006-04-03 at 23:43 +1000, Nick Coghlan wrote:
>
>
>>What do you think of a "format" builtin function that accepts the format as
>>the first argument (similar to printf).
>>
>>The version on my harddrive permits positional arguments via $1, $2, etc, as
>>well as string formatting (by sticking the format code in square brackets
>>between the $ and the identifier). Keyword arguments still work, naturally.
>>
>>And if you don't want formatting, you just leave out the square brackets.
>
>
> I'm not totally sure I would need a builtin. If I look at the two
> sources of $-strings in an app like Mailman, I'll see 1) literal human
> readable/translatable strings in the source code, 2) human entered
> strings that come from a web form.
>
> In the first case, all string formatting will funnel through one
> bottleneck function, which will do the catalog lookup, frame variable
> discovery, and substitution all in one fell swoop. So there, the
> builtin doesn't buy you much convenience.
Well, error messages are a common place I use %. So:
assert path.startswith(prefix), (
"%r should start with %r" % (path, prefix))
assert path.startswith(prefix), (
$"${repr(path)} should start with ${repr(prefix)}")
assert path.startswith(prefix), (
"$path should start with $prefix".substitute(
path=repr(path), prefix=repr(prefix))
The second example assumes that you can include full expressions,
otherwise that example would start looking really unpleasant. As it is,
the first example still looks more-or-less the best, and it's too bad
$-based substitution doesn't include it. I'm not sure how it would
include it, unless there was something like $=path, or $<path>, or
$`path` or something. I dunno, none of those are very appealing.
str.substitute isn't too bad, except that "substitute" feels a little
long-winded (compared to, say, str.format). If "$path".format() worked,
that'd be nice, but even though it's not that hard to implement, it
breaks a lot of expectations.
Anyway, that's one example. Any non-i18n'd code will likely have a fair
amount of string substitution which isn't otherwise wrapped in any routines.
--
Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org
More information about the Python-3000
mailing list