在字符串中寻找目标最后一次出现的位置(python)

# Define a procedure, find_last, that takes as input
# two strings, a search string and a target string,
# and returns the last position in the search string
# where the target string appears, or -1 if there
# are no occurrences.
#
# Example: find_last('aaaa', 'a') returns 3


# Make sure your procedure has a return statement.


def find_last(string,str):
    last_position=-1
    while True:
        position=string.find(str,last_position+1)
        if position==-1:
            return last_position
        last_position=position

不能返回position,因为position最终可能是-1.我们要返回最后一个目标出现的位置,应该返回last_position,因为他是前一个position的有效位置传递。当position为-1时,last_position保存了上一个position有效位置。这里先定义last_position初值为-1,从第一个(位置为0)字符开始查询,当没有一个目标位置被检索到时直接返回-1,否则从这个目标的下一个位置继续检索,直到position为-1或者检索结束为止。

下面是测试:


#print find_last('aaaa', 'a')
#>>> 3


#print find_last('aaaaa', 'aa')
#>>> 3


#print find_last('aaaa', 'b')
#>>> -1


#print find_last("111111111", "1")
#>>> 8


#print find_last("222222222", "")
#>>> 9


#print find_last("", "3")
#>>> -1


#print find_last("", "")
#>>> 0







  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值