Python函数return返回多余括号与引号的原因咨询
为什么第一个return的输出会带多余的括号和引号?
先贴出你的代码方便大家理解:
def find(the_string, search_this): if search_this in the_string: a = the_string.find(search_this) # 返回结果不符合预期 return (search_this, "found at", str(a)) else: # 是期望的正确输出 return (search_this + " was not found at " + the_string) print(find("qweabc","abc")) print(find("abcd", "xyz"))
这俩return的输出差异,核心原因是返回值的类型不一样:
- 第一个
return里,你用逗号分隔了三个值,哪怕加了括号,这本质是返回了一个元组(tuple)。Python的print函数在打印元组时,会直接输出它的“原生结构”——也就是包含括号,每个字符串元素也会带引号,所以你看到了('abc', 'found at', '3')。 - 第二个
return里的括号其实只是用来包裹字符串拼接表达式的(优先级用),里面的+操作把几个字符串拼成了一个整体,最终返回的是单个字符串。print打印字符串时,只会输出字符串的内容,不会额外带上引号或括号,所以输出符合你的预期。
要修复第一个return的问题,只要把它改成返回单个字符串就行,用f-string会更简洁易读:
def find(the_string, search_this): if search_this in the_string: a = the_string.find(search_this) return f"{search_this} found at {a}" else: return f"{search_this} was not found at {the_string}"
现在运行代码,两次print的输出就都会是你想要的格式了~
内容的提问来源于stack exchange,提问作者Zelda
相关产品推荐
相关产品推荐

