我正在学习python,我的任务是这样的:
- 定义名为is_substring的函数
- 使其接受两个参数
- 编写程序,检查是否已接受的第一个参数是第二个参数的子字符串
- 使它遍历字符串中的索引位置
- 在每个位置检查当前条带是否等于目标子字符串,相应地返回true或false
这是我的代码:
def is_substring(target, string):
for x in range(len(string)):
return x==target
print(is_substring('bad', 'abracadabra'))
print(is_substring('dab', 'abracadabra'))
对于第一个调用,它工作正常,但是对于第二个调用,它说false而不是true。有人可以告诉我为什么吗?
编写的代码没有多大意义。其中有许多不必要的操作。
在这里,您只是在字符串长度之外生成一个索引:
因此,您的操作是说“返回子字符串和索引x之间比较的布尔值”,此处没有任何作用。
您需要做的就是使用关键字“ in”检查字符串是否为子字符串:
x
here is the index itself, as in, 0, 1, 2, 3, 4, ....What you need is
string[x]
to get the character at the index.However a slice uses the notation
[start:stop:step]
where the step is optional.Here you need a slice of the length of the substring you are checking, length is fetched using the function
len
. So a slice at indexx
with lengthlen(target)
isstring[x: len(target) + x]