str1 = "hello,world"
# 正确的范围
print(str1.find("d", 0, len(str1)))
# 错误的范围
print(str1.find("d", 0 ,len(str1)-1))
第一个print输出的是正确的结果10
第二个print输出的是-1
python中索引取值一般是左闭右开,比如对于字符串s,s[0:11]就是取0-10的字符串,而s[0:10]则是取0-9的字符串,切片区间右边索引的值不会被选择,所以你这里的第二个的查找区间就不包含d了,找不到自然返回-1
find() 方法用于检索字符串中是否包含目标字符串,如果包含,则返回第一次出现该字符串的索引;反之,则返回 -1。
你第一个指定了 end参数为11,那么就是相当于从头检索到结尾,发现了 d的索引为10,所以输出10
第二个指定了end参数为10,那么就相当于从头检索到倒数第二位,就是l的位置,相当于“hello,worl” ,在这个字符串里面找d是不存在的,所以返回的是-1
有帮助的话,帮忙点击一下采纳谢谢
Python里字符串的find()、index()方法是不包含end下标的,具体可以参考一下Python源码的注释
def find(self, sub, start=None, end=None):
"""
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return 0
文档里没有明确说不包含end下标,但是根据惯例以及执行结果可以推出来