查找字符串中子字符串最后一次出现的索引 [英] Find index of last occurrence of a substring in a string

查看:51
本文介绍了查找字符串中子字符串最后一次出现的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在给定的输入字符串 str 中找到某个子字符串最后一次出现的位置(或索引).

例如,假设输入字符串是str = 'hello',子字符串是target = 'l',那么它应该输出3.

我该怎么做?

解决方案

使用 .rfind():

<预><代码>>>>s = '你好'>>>s.rfind('l')3

也不要使用 str 作为变量名,否则你会隐藏内置的 str().

I want to find the position (or index) of the last occurrence of a certain substring in given input string str.

For example, suppose the input string is str = 'hello' and the substring is target = 'l', then it should output 3.

How can I do this?

解决方案

Use .rfind():

>>> s = 'hello'
>>> s.rfind('l')
3

Also don't use str as variable name or you'll shadow the built-in str().

这篇关于查找字符串中子字符串最后一次出现的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆