return语句返回多余的撇号和括号,我不知道为什么。
此代码查找字符串中是否存在子字符串。
def find(the_string, search_this):
if search_this in the_string:
a = the_string.find(search_this)
# returns the unexpected
return (search_this, "found at", str(a))
else:
# the correct output I am looking for
return (search_this + " was not found at " + the_string)
print(find("qweabc","abc"))
print(find("abcd", "xyz"))
第一个return语句向我返回一个打印语句,这是不希望的。
示例:('abc', 'found at', '3')
第二个return语句以打印语句返回我,这是我要查找的语句:
示例:xyz was not found at abcd
打印出来后,为什么第一个return语句带有多余的括号和撇号?
答案 0 :(得分:1)
使用return (search_this, "found at", str(a))
时,您正在创建一个tuple
。
您可以这样操作(Python 2.6
或更高版本):
return "{} found at {}".format(search_this, str(a))
或者您可以这样做(Python 3.6
或更高版本):
return f"{search_this} found at {str(a)}"
测试您的示例:
def find(the_string, search_this):
if search_this in the_string:
a = the_string.find(search_this)
return f"{search_this} found at {str(a)}"
else:
return (search_this + " was not found at " + the_string)
print(find("qweabc","abc"))
print(find("abcd", "xyz"))
output:
abc found at 3
xyz was not found at abcd
答案 1 :(得分:0)
您要替换
return (search_this, "found at", str(a))
与return (search_this + "found at" + str(a))
或更可取的是:return "{} found at {}".format(search_this, a)
答案 2 :(得分:0)
此表达式创建三个字符串的tuple
。在Python中,tuple
与列表类似:
In [138]: ('one', 'two', 'three')
Out[138]: ('one', 'two', 'three')
此表达式将三个字符串连接为一个字符串:
In [139]: ('one'+ 'two'+ 'three')
Out[139]: 'onetwothree'
在这种情况下,()
只是一个分组工具,请不要进行更改:
In [140]: 'one'+ 'two'+ 'three'
Out[140]: 'onetwothree'
要使用一个项(例如字符串)创建tuple
,则必须包含逗号:
In [141]: ('one'+ 'two'+ 'three',)
Out[141]: ('onetwothree',)
实际上,创建元组的是逗号(比()
更重要)
In [142]: 'one', 'two', 'three'
Out[142]: ('one', 'two', 'three')
还有一个列表供比较:
In [143]: ['one', 'two', 'three']
Out[143]: ['one', 'two', 'three']
这种关于字符串,元组和列表的表示法一开始可能会令人困惑,但值得学习。
和另一个变体-将三个字符串传递给print
函数:
In [144]: print('one', 'two', 'three')
one two three