python: cannot concatenate 'str' and 'tuple' objects (it should works!)

别说谁变了你拦得住时间么 提交于 2021-02-16 04:43:47

问题


I have a code:

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

And after this my application displays:

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

I don't know what I make wrong. print tuple('1, 2, 3'.split(', ')) works properly.


回答1:


print tuple(something)

may work because print will do an implicit str() on the argument, but and expression like

"" + ()

does not work. The fact that you can print them individually doesn't make a difference, you can't concatenate a string and a tuple, you have to convert either one of them. I.e.

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

However, depending on str() for conversion probably won't give the desired results. Join them neatly using a separator using ",".join for example




回答2:


Why do you think it should work?

try:

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



回答3:


Change it to

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



回答4:


Why tuple by splitting, you have string for one ready except the paranthesis, why not:

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



回答5:


No need of tuple(), following works,

outstr = str((w,t)) # (w,t) is my tuple


来源:https://stackoverflow.com/questions/3609637/python-cannot-concatenate-str-and-tuple-objects-it-should-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!