[Python-Dev] "%%s %s"%"hi"%ho" works here and not there

Skip Montanaro skip@pobox.com
Mon, 16 Jun 2003 07:47:22 -0500


    Hunter> In irc, I gave this unusually compact line as an answer to a
    Hunter> slightly related question: "%%s %s"%"hi"%ho"

    Hunter> It ended up not working on a lot of the other users
    Hunter> systems. "%%s %s"%a%b worked though on all i believe.

I don't see you your hi/ho example can work as written, since there are an
odd number of quotes.  Adding an extra quote in the obvious place makes it
work for me:

    >>> "%%s %s"%"hi"%ho" 
      File "<stdin>", line 1
        "%%s %s"%"hi"%ho" 
                         ^
    SyntaxError: EOL while scanning single-quoted string
    >>> "%%s %s"%"hi"%"ho" 
    'ho hi'

You can get carried away with the concept as well:

    >>> "%%%%s %%s %s"%"hi"%"ho"%"hum" 
    'hum ho hi'
    >>> "%%%%%%%%s %%%%s %%s %s"%"hi"%"ho"%"hum"%"harvey" 
    'harvey hum ho hi'

Should people be tempted to do this sort of thing on a regular basis, I
suggest you avoid it unless you're competing in an obfuscated Python
contest.  I've used the technique (though with just with two levels of
interpolation!) a few times and always found it a bit challenging to go back
and read later.  I think it's better to split into multiple statements using
a temporary variable so it's obvious what gets substituted when (also, a
little whitespace never hurts):

    >>> fmt = "%%s %s" % "hi"
    >>> fmt
    '%s hi'
    >>> fmt % "ho"
    'ho hi'

Skip