python:无法连接“str”和“tuple”对象(它应该可以工作!)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3609637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:55:51  来源:igfitidea点击:

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

pythonstringtuples

提问by CarolusPl

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, 3Traceback (most recent call last): File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, in RunScript exec codeObject in main.dictFile "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回溯(最近一次调用):文件“C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py”,第 312 行,在main中的 RunScript exec codeObject 。dictFile "C:\Documents and Settings\k.pawlowski\Desktop\atsserver.py", line 165, in print "bug tuple" + tuple(temp.split(', ')) TypeError: cannot concatenate 'str' and “元组”对象

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

我不知道我做错了什么。print tuple('1, 2, 3'.split(', '))正常工作。

采纳答案by Ivo van der Wijk

print tuple(something)

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

可能会起作用,因为 print 将对参数执行隐式 str() ,但是和表达式类似

"" + ()

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.

不起作用。您可以单独打印它们并没有什么区别,您不能连接字符串和元组,您必须转换它们中的任何一个。IE

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

但是,根据 str() 进行转换可能不会给出所需的结果。例如,使用“,”.join 使用分隔符将它们整齐地连接起来

回答by Moe

Change it to

将其更改为

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

回答by Maciej Kucharz

Why do you think it should work?

为什么你认为它应该起作用?

try:

尝试:

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

回答by Tony Veijalainen

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

为什么通过拆分元组,除了括号之外,你已经准备好了一个字符串,为什么不:

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

回答by samsamara

No need of tuple(), following works,

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

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