python:无法连接“str”和“元组”对象(它应该有效!)

发布于 2024-09-16 20:45:32 字数 719 浏览 2 评论 0原文

我有一个代码:

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

之后我的应用程序显示:

错误 1、2、3 回溯(最近的 最后调用):文件 “C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py”, RunScript 中的第 312 行 exec codeObject in ma​​in.dict 文件“C:\Documents and Settings\k.pawlowski\Desktop\atsserver.py", 第 165 行,在 print "bug tuple " + tuple(temp.split(', ')) 类型错误: 无法连接“str”和“tuple” 对象

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

海螺姑娘 2024-09-23 20:45:32
print tuple(something)

可能会起作用,因为 print 会对参数执行隐式 str() 操作,但像这样的表达式

"" + ()

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

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

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

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

浮生未歇 2024-09-23 20:45:32

为什么你认为它应该有效?

尝试:

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

Why do you think it should work?

try:

print "bug tuple " + str(tuple(temp.split(', ')))
起风了 2024-09-23 20:45:32

将其更改为

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

Change it to

print "bug tuple ", tuple(temp.split(', '))
婴鹅 2024-09-23 20:45:32

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

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

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

print "bug tuple (%s)" % '1, 2, 3'
颜漓半夏 2024-09-23 20:45:32

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

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

No need of tuple(), following works,

outstr = str((w,t)) # (w,t) is my tuple
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文