1
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

2
  • from: stackoverflow.com/questions/1455602/… print "this is a tuple: %s" % (divmod(10,20),) Commented Jul 25, 2013 at 20:58
  • I think was a good question. Nothing obvious about it! Pretty subtle, in my opinion. Very informative. Commented Jul 26, 2013 at 1:10

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Because .format is SO MUCH BETTER than the old % method, if for no other reason than your example right here.
((('hi',) + divmod(10,20))) also works. So tuples must unwrap themselves or something....
1
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

12 Comments

@MartijnPieters you're faster than me, hold on
You were a little too fast to post and not try first. :-)
'hi' + divmod(10,20) -> TypeError: cannot concatenate 'str' and 'tuple' objects
@RussW I know, What i said doesn't contradict that
@Jim giving up is the smart thing to do when MP posts an answer, but I STRIDE FORTH with a UNIQUE and much less optimal answer!
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.