Why does this (not) work?

Skip Montanaro skip at pobox.com
Tue Aug 19 17:41:01 EDT 2003


    Michael> But I want to use the * to make life easier to read, so I tried:

    >>>> ("test",)*3
    Michael> ('test', 'test', 'test')
    >>>> "%s - %s - %s" % ("test",)*3
    Michael> Traceback (most recent call last):
    Michael>   File "<stdin>", line 1, in ?
    Michael> TypeError: not enough arguments for format string
    >>>> 

That's because the % and * operators have the same precendence and group
left-to-right.  The above expression is equivalent to

    ("%s - %s - %s" % ("test",))*3

To force the * operation to be evaluated first you need to add some parens:

    ("%s - %s - %s" % (("test",))*3)

which works as expected:

    >>> "%s - %s - %s" % (("test",)*3)
    'test - test - test'

If you're worried about readability of large format operations, I suggest
you consider using dictionary expansion, e.g.:

    >>> "%(var)s - %(var)s - %(var)s" % {"var": "test"}
    'test - test - test'

or more commonly:

    >>> var = "test"
    >>> "%(var)s - %(var)s - %(var)s" % locals()
    'test - test - test'

Skip





More information about the Python-list mailing list