Why does this (not) work?

Cliff Wells logiplex at qwest.net
Tue Aug 19 23:54:34 CEST 2003


On Tue, 2003-08-19 at 14:25, Michael C. Neel wrote:
> I've got this string in which I need to sub in the same word several
> times; i.e:
> 
> >>> "%s - %s - %s" % ("test","test","test")
> 'test - test - test'
> >>>
> 
> But I want to use the * to make life easier to read, so I tried:
> 
> >>> ("test",)*3
> ('test', 'test', 'test')
> >>> "%s - %s - %s" % ("test",)*3
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: not enough arguments for format string
> >>>

> Any idea why the tuple to str to tuple works and not the tuple straight?

Because % has higher precedence than * (or rather they have equal
precedence and the expression is evaluated left to right) so the
expression becomes 

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

when what you meant was

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

Here's another approach:

>>> def fjoin(sep, s, n):
...     return sep.join(["%s"] * n) % ((s,) * n)
...
>>> fjoin(' - ', "test", 3)
'test - test - test'


Regards,

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726  (800) 735-0555






More information about the Python-list mailing list