查找字符串中第 n 次出现的子字符串 [英] Find the nth occurrence of substring in a string
问题描述
这看起来应该很简单,但我是 Python 新手,想用最 Python 化的方式来做.
This seems like it should be pretty trivial, but I am new at Python and want to do it the most Pythonic way.
我想找到对应于字符串中子字符串第 n 次出现的索引.
I want to find the index corresponding to the n'th occurrence of a substring within a string.
必须有一些与我想做的事情相同的事情
There's got to be something equivalent to what I WANT to do which is
mystring.find("substring", 2nd)
如何在 Python 中实现这一点?
How can you achieve this in Python?
推荐答案
Mark 的迭代方法将是通常的方法,我认为.
Mark's iterative approach would be the usual way, I think.
这里有一个字符串分割的替代方法,它通常对查找相关的过程很有用:
Here's an alternative with string-splitting, which can often be useful for finding-related processes:
def findnth(haystack, needle, n):
parts= haystack.split(needle, n+1)
if len(parts)<=n+1:
return -1
return len(haystack)-len(parts[-1])-len(needle)
这是一个快速(有点脏,因为你必须选择一些与针头不匹配的箔条)单线:
And here's a quick (and somewhat dirty, in that you have to choose some chaff that can't match the needle) one-liner:
'foo bar bar bar'.replace('bar', 'XXX', 1).find('bar')
这篇关于查找字符串中第 n 次出现的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!