python元组打印问题

foo*_*ion 1 python tuples string-formatting

print '%d:%02d' % divmod(10,20)
Run Code Online (Sandbox Code Playgroud)

得到我想要的:

0:10
Run Code Online (Sandbox Code Playgroud)

然而

print '%s %d:%02d' % ('hi', divmod(10,20))
Run Code Online (Sandbox Code Playgroud)

结果是:

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
Run Code Online (Sandbox Code Playgroud)

如何修复第二个print语句以使其有效?

我认为有一个更简单的解决方案

m = divmod(10,20)
print m[0], m[1]
Run Code Online (Sandbox Code Playgroud)

或使用python 3或format().

我觉得我错过了一些明显的东西

Mar*_*ers 5

你是嵌套元组; 连接:

print '%s %d:%02d' % (('hi',) + divmod(10,20))
Run Code Online (Sandbox Code Playgroud)

现在,您创建一个包含3个元素的元组,并且字符串格式化工作正常.

演示:

>>> print '%s %d:%02d' % (('hi',) + divmod(10,20))
hi 0:10
Run Code Online (Sandbox Code Playgroud)

并说明差异:

>>> ('hi', divmod(10,20))
('hi', (0, 10))
>>> (('hi',) + divmod(10,20))
('hi', 0, 10)
Run Code Online (Sandbox Code Playgroud)

或者,使用str.format():

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

这里我们插入第一个参数({0}),然后插入第二个参数的第一个元素({1[0]}将值格式化为整数),然后插入第二个参数的第二个元素({1[1]}将值格式化为2位数字和前导零的整数) .