简体   繁体   中英

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM