This seems like it should be pretty trivial, but I am new at Python and want to do it the most Pythonic way.
I want to find the n'th occurrence of a substring in a string.
There's got to be something equivalent to what I WANT to do which is
mystring.find("substring", 2nd)
How can you achieve this in Python?
Understanding that regex is not always the best solution, I'd probably use one here:
This is the answer you really want:
Here's another
re
+itertools
version that should work when searching for either astr
or aRegexpObject
. I will freely admit that this is likely over-engineered, but for some reason it entertained me.How about:
I'd probably do something like this, using the find function that takes an index parameter:
It's not particularly Pythonic I guess, but it's simple. You could do it using recursion instead:
It's a functional way to solve it, but I don't know if that makes it more Pythonic.