gpt4 book ai didi

python 元组打印问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:50 24 4
gpt4 key购买 nike

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

结果是我想要的:

0:10

不过

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

结果:

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

如何修复第二个打印语句以使其正常工作?

我认为有比这更简单的解决方案

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

或使用 python 3 或 format()。

我觉得我遗漏了一些明显的东西

最佳答案

你是嵌套元组;改为连接:

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

现在您创建了一个包含 3 个元素的元组并且字符串格式有效。

演示:

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

为了说明区别:

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

或者,使用 str.format():

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

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

关于python 元组打印问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17868546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com