Python索引不止一次

标签 python string indexing substring

我知道 .index() 将返回子字符串在 python 中的位置。 但是,我想要的是第 n 次找到子字符串所在的位置,这将像这样工作:

>> s = 'abcdefacbdea'
>> s.index('a')
0
>> s.nindex('a', 1)
6
>>s.nindex('a', 2)
11

有没有办法在 python 中做到这一点?

最佳答案

怎么样...

def nindex(mystr, substr, n=0, index=0):
    for _ in xrange(n+1):
        index = mystr.index(substr, index) + 1
    return index - 1

观测值:为 str.index()确实如此,nindex() 在未找到 substr 时引发 ValueError

关于Python索引不止一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3380654/

相关文章:

c - 指向结构体指针的指针

c# - collection/string.Contains vs collection/string.IndexOf

python - 在python上查找mac地址

python - 如何将 urlencode 更改为 python 字典

python - 如何将行值与前一行值进行比较?

javascript - 使用jQuery从字符串中获取倒数第二个字符位置

MySQL 字符串操作以计算字段中的值

python - 我已经安装了 scikit-learn/sklearn。运行python文件后出现此错误

sql-server - SQL Server : Geography search performance - query nearest stores

javascript - 在每个 block 的 Handlebars 内部使用索引值