+3 votes
in Programming Languages by (19.3k points)
If a substring appears several times in a string, how can I find the position of the last occurrence of the substring in the string?

E.g.

str = 'This is a pen. This is a pen. This is a pen'

The position of the last "pen" is 40, so the answer should be 40.

1 Answer

0 votes
by (33.7k points)

You can use either rfind() or rindex() function to get the position of the last occurrence of the substring.

E.g.

>>> aa='This is a pen. This is a pen. This is a pen'
>>> aa.rfind('pen')
40
>>> aa.rindex('pen')
40

...