Why does this (not) work?

Michael C. Neel neel at mediapulse.com
Tue Aug 19 23:25:19 CEST 2003


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
>>>

Which seemed like a good idea, but after some playing around I found
that:

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

Did work.  Odd because:

>>> type(("test",)*3)
<type 'tuple'>
>>> type(eval(str(("test",)*3)))
<type 'tuple'>
>>>

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

Mike





More information about the Python-list mailing list