实现一个函数,在一句话中查找某个单词的算法,存在返回索引号,否则返回False.

题目30:自己实现一个函数,在一句话中查找某个单词的算法,存在返回索引号,否则返回False.

提示:使用坐标遍历句子的每一个位置。
使用查找单词的长度结合使用切片来查找单词;
例如 s=[i:i+len(单词)]
遍历字符串:1、直接取字符2、基于位置遍历
知识点:Len查看学列长度:

>>> len("123")
3
>>> len([1,2,3])
3
>>> len((1,2,3))
3
>>> len({1:1,2:2})
2
>>> len(123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> len(str(123))
3

在这里插入图片描述
方法1:

sentence="I am good"
def find_word_index(sentence,word):
    word_length = len(word)
    for i in range(len(sentence)-word_length+1):
        if  sentence[i:i+word_length] == word:
            return i
    return -1
print(find_word_index(sentence,"good"))

在这里插入图片描述
**注意:**函数只要返回return -1,函数中的所有代码都不会被执行。

找出某文件中的多个单词:

sentence="I am good good good boy!"
def find_word_index(sentence,word):
    position_list=[]
    word_length = len(word)
    for i in range(len(sentence)-word_length+1):
        if  sentence[i:i+word_length] == word:
            position_list.append(i)
    return position_list
print(find_word_index(sentence,"good"))

在这里插入图片描述
方法2:

sentence="I am good  good good boy!"
def find_word_index(sentence,word):
    position_list=[]
    word_length = len(word)
    for i in range(len(sentence)-word_length+1):
        for j in  range(word_length): 
            if  sentence[i+j] != word[j]:
                break
        else:
            position_list.append(i)
    return position_list
print(find_word_index(sentence,"good"))

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值