[英]python tuple print issue
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位數字和前導零的整數)。
print '%s %d:%02d' % ('hi',divmod(10,20)[0], divmod(10,20)[1])
^ ^ ^
1 2 3
帶逗號的括號表示元組,帶連接(+)的括號將返回字符串。
您需要一個3元組用於3個輸入,如下所示
您正在將字符串和元組傳遞給格式的元組,而不是字符串和兩個整數。 這有效:
print '%s %d:%02d' % (('hi',) + divmod(10,20))
有一個元組串聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.