why does the % string format operator only take tuples?

Tim Peters tim.one at home.com
Tue Apr 3 20:24:10 EDT 2001


[Ram Bhamidipaty]
> Its possible to do this:
>   print "%d %d" % (1,2)
> but not this:
>   print "%d %d" % [1,2]
>
> Why?
>
> I know I can convert the list to a tuple. I want to know
> if there is a reason for % not taking lists as well as tuples.

Because "%" does accept lists, but not in the same way; e.g.,

>>> result = [1, 2]
>>> print "Result list is: %s." % result
Result list is: [1, 2].
>>>

> Does anyone else think it would be a good idea of the % operator
> were extended to also handle lists?

Not now -- it would break code like the above.  More generally, "%" *could*
have been defined to work on sequences, but, since a string is a sequence in
Python too, that would have harbored nastier surprises.

thh-tuple()-builtin-is-your-friend-ly y'rs  - tim





More information about the Python-list mailing list