Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of last occurrence of a substring in a string

Tags:

python

string

I want to find the position (or index) of the last occurrence of a certain substring in given input string str.

For example, suppose the input string is str = 'hello' and the substring is target = 'l', then it should output 3.

How can I do this?

like image 534
Parth Soni Avatar asked Mar 05 '12 19:03

Parth Soni


People also ask

How do you find the last occurrence of a substring in a string?

The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found. The rfind() method is almost the same as the rindex() method.

How do you find the last index of a substring in a string in Python?

Python String rindex() Method Python string method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end].

What is the index of the last character in a string?

Strings are zero-indexed: The index of a string's first character is 0 , and the index of a string's last character is the length of the string minus 1.

How do you find last index?

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex .


2 Answers

Use .rfind():

>>> s = 'hello' >>> s.rfind('l') 3 

Also don't use str as variable name or you'll shadow the built-in str().

like image 56
Rik Poggi Avatar answered Oct 16 '22 08:10

Rik Poggi


You can use rfind() or rindex()
Python2 links: rfind() rindex()

>>> s = 'Hello StackOverflow Hi everybody'  >>> print( s.rfind('H') ) 20  >>> print( s.rindex('H') ) 20  >>> print( s.rfind('other') ) -1  >>> print( s.rindex('other') ) Traceback (most recent call last):   File "<stdin>", line 1, in <module> ValueError: substring not found 

The difference is when the substring is not found, rfind() returns -1 while rindex() raises an exception ValueError (Python2 link: ValueError).

If you do not want to check the rfind() return code -1, you may prefer rindex() that will provide an understandable error message. Else you may search for minutes where the unexpected value -1 is coming from within your code...


Example: Search of last newline character

>>> txt = '''first line ... second line ... third line'''  >>> txt.rfind('\n') 22  >>> txt.rindex('\n') 22 
like image 24
oHo Avatar answered Oct 16 '22 08:10

oHo