string interpolation for python

Chris Angelico rosuav at gmail.com
Mon Apr 2 05:56:27 EDT 2012


On Mon, Apr 2, 2012 at 7:11 PM, Yingjie Lan <lanyjie at yahoo.com> wrote:
> I believe non of the other three alternatives are as terse and readable.
> We've got template based, formatting with dict, formatting with tuple.
> They all require the coder extra effort:
>
> Both template based and dict-based formatting require writing the
> identifier three times:
>
>>>> name = 'Peter'
>>>> "Are you %(name)s"%{'name':name}
>
> If dynamic string is used:
>>>> "Are you $name$?"

Yes, it's more compact. But it's also more magic. However, there's an
alternative that's almost as compact. The only requirement is that you
use a two-character token instead of your dollar sign: a double-quote
and a plus.

>>> "Are you "+name+"?"

That allows arbitrary expressions and everything.

> Of course, the old C style way:
>
>>>> "Are you %s?"%name
>
> Almost as terse, but not as readable, especially
> when there are many parts to substitute --
> the coder and reader need to be careful
> to make sure the sequence is correct.

I quite like this notation, personally. It's convenient, and is
supported (with variants) in quite a few C-derived languages (and, in
spite of the massive syntactic differences, Python does have C
heritage).

> Why the Python community is so
> hostile to new things now?
> Python has merits,
> but it is far from being perfect.

Hey now, no need to get defensive :) Thing is, it's up to you to
demonstrate that your proposal justifies itself. You're proposing to
create a massive backward-compatibility issue, so you need to prove
that your new way of formatting strings is sufficiently awesome to be
able to say "Well, you need Python 3.4+ to use this".

ChrisA



More information about the Python-list mailing list