2010-08-31 37 views
8

我有一個代碼:蟒蛇:不能連接 '海峽' 和 '元組' 的對象(!它應該作品)

print "bug " + data[str.find(data,'%')+2:-1] 
temp = data[str.find(data,'%')+2:-1] 
time.sleep(1) 
print "bug tuple " + tuple(temp.split(', ')) 

並在此之後我的應用程序顯示:

bug 1, 2, 3 Traceback (most recent call last): File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, in RunScript exec codeObject in main.dict File "C:\Documents and Settings\k.pawlowski\Desktop\atsserver.py", line 165, in print "bug tuple " + tuple(temp.split(', ')) TypeError: cannot concatenate 'str' and 'tuple' objects

我不知道我做錯了什麼。 打印元組('1,2,3'.split(','))正常工作。

+2

如有疑問,請在互動翻譯器中進行測試! '>>>'ftw! – jathanism 2010-08-31 14:00:49

回答

14
print tuple(something) 

可以工作,因爲印刷會做參數隱式STR(),但表達類似

"" +() 

不起作用。事實上,你可以單獨打印它們沒有什麼不同,你不能連接一個字符串和一個元組,你必須轉換它們中的任何一個。即

print "foo" + str(tuple("bar")) 

但是,根據用於轉換的str()可能不會給出所需的結果。加入他們用整齊的用分隔符「」加入例如

2

將其更改爲

print "bug tuple ", tuple(temp.split(', ')) 
+0

這是它;)謝謝。經過幾個小時的編碼,我很愚蠢......;) – CarolusPl 2010-08-31 14:06:00

+0

得到一些睡眠... – PaulMcG 2010-08-31 14:36:32

3

爲什麼你認爲它應該工作?

嘗試:

print "bug tuple " + str(tuple(temp.split(', '))) 
0

爲什麼通過拆分元組,你有串一個除了paranthesis,爲什麼不準備:

print "bug tuple (%s)" % '1, 2, 3' 
0

不需要的tuple(),以下的作品,

outstr = str((w,t)) # (w,t) is my tuple 
相關問題