2013-07-25 142 views
1
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或格式()簡單的解決方案。

我覺得我失去了一些東西明顯

+0

從:http://stackoverflow.com/questions/1455602/printing-tuple-with-string-formatting-in-python 打印 「這是一個元組:%S」 %(divmod(10, 20),) – sihrc

+0

我認爲這是一個很好的問題。沒什麼明顯的!在我看來,非常微妙。非常豐富。 – Jiminion

回答

5

您是嵌套元組; concatenate改爲:

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位數和前導零的整數)。

+0

+1因爲'.format'比舊的'%'方法好得多,如果沒有其他原因比你的例子就在這兒。 – SethMMorton

+1

oh jezus that'.format'回答剛接觸我的 – Stephan

+0

((('hi',)+ divmod(10,20)))也有效。所以元組必須解開自己或東西.... – Jiminion

1
print '%s %d:%02d' % ('hi',divmod(10,20)[0], divmod(10,20)[1]) 
        ^  ^    ^
         1   2     3 

括號用逗號表示元組,與級聯(+)將的括號返回字符串。

你需要一個3元組爲3個輸入,如圖

+0

@MartijnPieters你比我快,堅持 – Stephan

+0

你有點太快,無法發佈,而不是先嚐試。:-) –

+0

''hi'+ divmod(10,20)' - >'TypeError:無法連接'str'和'元組'對象 – RussW

0

您將一個字符串和一個元組傳遞給格式的元組,而不是一個字符串和兩個整數。這工作:

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

有一個元組連接。