[Tutor] modulus

Steven D'Aprano steve at pearwood.info
Wed Nov 16 17:09:09 CET 2011


Wayne Werner wrote:

> In this case it's not actually modulus, it's just the syntax for string
> formatting. I'm not sure *what* the reasoning behind the % was, but that's
> the way it is.

I believe the designers of the C programming language are to blame.

[...]
> In old style formatting, you use a string with format specifiers (%s, %d,
> etc.) followed by a tuple of arguments. Here, the lengths have to match
> exactly - if you have one specifier then you must have a 1-element tuple.

That's actually wrong. If you have one specifier, you must have one 
object of any sort *except* a tuple.

 >>> "%s" % 42  # One object not a tuple.
'42'

But if you have a tuple, the % formatting will try to use each element 
in the tuple separately:

 >>> "%s" % (23, 42)  # One object which is a tuple
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting


So if you actually want to use a tuple as the object, you need to wrap 
it in a single item tuple:

 >>> "%s" % ((23, 42),)  # Tuple inside a tuple.
'(23, 42)'


-- 
Steven


More information about the Tutor mailing list