In section "1.12. Formatting strings", "Example 1.29.
String formatting vs. concatenating", points 3 and 4
claim that it is required to use:
>>> userCount = 6
>>> print "Users connected: %d" % (userCount, )
Users connected: 6
However, on my two Python systems (ActivePython 2.1.1
on win32, and Python 2.1 on linux2) I can also use the
following two alternatives:
>>> userCount = 6
>>> print "Users connected: %d" % (userCount)
Users connected: 6
>>> print "Users connected: %d" % userCount
Users connected: 6
To some extend, this contradicts the explanation given
in point 3 below the example: "(userCount, ) is a tuple
with one element. Yes, the syntax is a little strange,
but there's a good reason for it: it's unambiguously a
tuple. In fact, you can always include a comma after
the last element when defining a list, tuple, or
dictionary, but the comma is required when defining a
tuple with one element. If the comma weren't required,
Python wouldn't know whether (userCount) was a tuple
with one element or just the value of userCount."
Maybe it is something in Python 2.1 (and above?), but
the claim that "the comma is required when defining a
tuple with one element" is not true...
Hope this helps in improving "Dive Into Python", which
I really love as a jumpstarter into Python programming.
Frank
Logged In: YES
user_id=194751
I could be missing the point here :-)
The claim that "the comma is required when defining a tuple
with one element" is probably correct after all...
What I observed is that the print statement can take single
values behind the "%" next, not just tuples.
However, an explanation of the following might help:
>>> x = 1
>>> y = (1)
>>> z = (1, )
>>> type(x)
<type 'int'>
>>> type(y)
<type 'int'>
>>> type(z)
<type 'tuple'>
In my opinion it shows the difference between "1", "(1)" and
"(1, )", where "(1, )" is the only true tuple.
HTH,
Frank