[英]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(). 或使用python 3或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. 现在,您创建了一个由3个元素组成的元组,并且字符串格式生效。
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()
: 或者,使用
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). 这里我们先插入第一个参数(
{0}
),然后插入第二个参数的第一个元素( {1[0]}
,将值格式化为整数),然后插入第二个参数的第二个元素( {1[1]}
,将值格式化为2位数字和前导零的整数)。
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 您需要一个3元组用于3个输入,如下所示
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. 有一个元组串联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.