python:无法连接“str"和“tuple"对象(它应该可以工作!) [英] python: cannot concatenate 'str' and 'tuple' objects (it should works!)
问题描述
我有一个代码:
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:
错误 1、2、3追溯(最近最后调用):文件"C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",第 312 行,在 RunScript 中exec codeObject in main.dict File "C:\Documents and设置\k.pawlowski\Desktop\atsserver.py",第 165 行,在打印错误元组"+ 元组(temp.split(','))类型错误:不能连接'str'和'tuple'对象
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
我不知道我做错了什么.print tuple('1, 2, 3'.split(', ')) 正常工作.
I don't know what I make wrong. print tuple('1, 2, 3'.split(', ')) works properly.
推荐答案
print tuple(something)
可能会起作用,因为 print 会在参数上执行隐式 str(),但是和表达式类似
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"))
但是,根据 str() 进行转换可能不会给出所需的结果.使用分隔符将它们整齐地连接起来,例如使用,".join
However, depending on str() for conversion probably won't give the desired results. Join them neatly using a separator using ",".join for example
这篇关于python:无法连接“str"和“tuple"对象(它应该可以工作!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!