foosion
foosion

Reputation: 7928

python tuple print issue

print '%d:%02d' % divmod(10,20)

results in what I want:

0:10

However

print '%s %d:%02d' % ('hi', divmod(10,20))

results in:

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print '%s %d:%02d' % ('hi', divmod(10,20))
TypeError: %d format: a number is required, not tuple

How do I fix the second print statement so that it works?

I thought there was a simpler solution than

m = divmod(10,20)
print m[0], m[1]

or using python 3 or format().

I feel I'm missing something obvious

Upvotes: 1

Views: 1662

Answers (3)

Stephan
Stephan

Reputation: 18041

print '%s %d:%02d' % ('hi',divmod(10,20)[0], divmod(10,20)[1])
                       ^         ^                 ^
                       1         2                 3

Parentheses with commas indicate tuples, parens with concatenation (+) will return strings.

You need a 3-tuple for 3 inputs as shown

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1125028

You are nesting tuples; concatenate instead:

print '%s %d:%02d' % (('hi',) + divmod(10,20))

Now you create a tuple of 3 elements and the string formatting works.

Demo:

>>> print '%s %d:%02d' % (('hi',) + divmod(10,20))
hi 0:10

and to illustrate the difference:

>>> ('hi', divmod(10,20))
('hi', (0, 10))
>>> (('hi',) + divmod(10,20))
('hi', 0, 10)

Alternatively, use str.format():

>>> print '{0} {1[0]:d}:{1[1]:02d}'.format('hi', divmod(10, 20))
hi 0:10

Here we interpolate the first argument ({0}), then the first element of the second argument ({1[0]}, formatting the value as an integer), then the second element of the second argument ({1[1]}, formatting the value as an integer with 2 digits and leading zeros).

Upvotes: 5

Paulo Bu
Paulo Bu

Reputation: 29804

You're passing a string and a tuple to the format's tuple, not a string and two ints. This works:

print '%s %d:%02d' % (('hi',) + divmod(10,20))

There is a tuple concatenation.

Upvotes: 0

Related Questions