在python中创建索引字符串中的单词的函数

2024-05-01 21:45:38 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的赋值,我被要求创建一个函数,如果单词在字符串中,则返回字符串中单词的索引;如果单词不在字符串中,则返回(-1)

bigstring = "I have trouble doing this assignment"
mywords = bigstring.split()
def FindIndexOfWord(all_words, target):
    index = mywords[target]
    for target in range(0, len(mywords)):
        if  target == mywords:
            return(index)
    return(-1)
print(FindIndexOfWord(mywords, "have"))

我很确定我的错在4号线。。。但我不知道如何返回单词在列表中的位置。非常感谢您的帮助!你知道吗


Tags: 函数字符串targetindexreturnhavethis单词
3条回答

可以对字符串使用.find(word)来获取单词的索引。你知道吗

要在alist中查找单词的索引,请使用.index()函数,并且为了安全起见,在找不到单词时退出代码,请使用异常。显示下图:

bigstring = "I have trouble doing this assignment"
mywords = bigstring.split()
def FindIndexOfWord(list,word):
    try:
        print(list.index(word))
    except ValueError:
        print(word," not in list.")

FindIndexOfWord(mywords,"have")

输出:

1

你犯了些小错误。 以下是正确的代码:

bigstring = "I have trouble doing this assignment"
mywords = bigstring.split()
def FindIndexOfWord(all_words, target):
    for i in range(len(mywords)):
        if  target == all_words[i]:
            return i
    return -1
print(FindIndexOfWord(mywords, "this"))

目标是字符串而不是整数,因此不能使用

index = mywords[target]

如果找到字符串else-1,则返回循环中使用的变量

相关问题 更多 >