我需要Python帮助 - 在函数内搜索

2 投票
6 回答
1609 浏览
提问于 2025-04-17 01:56
def find(word, letter):
    index = 0
    while index < len(word):
        if word[index] == letter:
            return index
        index = index + 1
    return -1

我明白了...

这个练习说:

修改 find 函数,让它有一个第三个参数,表示在单词中从哪个位置开始查找。

请原谅我这个新手的问题……当它说要修改 'find' 让它有一个第三个参数时,是指像这样 find(word,letter,thirdparameter),还是在函数定义里面加一个第三个参数呢?还有,关于在单词中从哪个位置开始查找,我不太确定我理解得对不对,是不是想要在单词的某个索引位置开始查找?

6 个回答

2

当它说要修改'find'函数,让它有一个第三个参数时...也就是find(word, letter, thirdparameter)

没错。

或者在函数定义里加一个第三个参数呢?

嗯。这是同样的意思。就是在函数定义里添加一个第三个参数。

2

这句话的意思是,你需要修改这个函数,让它多一个参数,这个参数就是在字符串中开始查找匹配的起始位置。

下面是修改之后的一些示例输出,可能会帮助你理解:

>>> find('abc abc', 'b', 0)  # starting at beginning, will find the first 'b'
1
>>> find('abc abc', 'b', 2)  # starting after first 'b', will find the second 'b'
5
>>> find('abc abc', 'b', 6)  # starting after both 'b's, won't find a match
-1
2

这个问题是在让你创建一个新的参数,用来指定开始查找的索引位置。新的函数格式大概是 find(letter, word, startindex)。它的工作方式是这样的:

>>> find('red blue', 'd', 0) # starts at index 0 and finds 'd' at index 2
2
>>> find('red blue', 'd', 3) # starts at index 3 and finds no d's
-1
>>> find('red blue', 'e', 3) # starts at index 3, so misses the 'e' at index 1
7

撰写回答