python中在一个字符串中查找另一个字符串。实现一个字符串的find函数。

156 篇文章 5 订阅
1.在一个字符串中查找另一个字符串
2.找到了返回第一次出现的位置
3.没找到返回-1
4.参数s1为源字符串,参数s2为要查找的字符串
def index_of_str(s1, s2):
    n1=len(s1)
    n2=len(s2)
    for i in range(n1-n2+1):
        if s1[i:i+n2]==s2:
            return i
    else:
            return -1
print(index_of_str('12abc34de5f', 'c34'))
方法二:
def index_of_str(s1, s2):
    lt=s1.split(s2,1)
    if len(lt)==1:
        return -1
    return len(lt[0])
print(index_of_str('12abc34de5f', 'c34'))

结果:4


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值