+3 votes
in Programming Languages by (75.1k 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

+1 vote
by (353k points)
selected by
 
Best answer

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


...