Is there any significant difference in term of speed other than potential overheads if we have to enclose s.index() within a try/except.

In (C)Python at least, find, index, rfind, rindex are all wrappers around an internal function any_find_slice.

The implementation is the same. The only difference is that index and rindex will raise a ValueError for you if it finds that the result of calling any_find_slice is -1.

If you went ahead and timed these you'd see how there's clearly no meaningful difference between them:

➜  ~ python -m perf timeit -s "s = 'a' * 1000 + 'b'" "s.find('b')"
Median +- std dev: 399 ns +- 7 ns
➜  ~ python -m perf timeit -s "s = 'a' * 1000 + 'b'" "s.index('b')"
Median +- std dev: 396 ns +- 3 ns

I'm using perf for the timings here.

I'm guessing in other implementations of Python this shouldn't differ. Both methods do the same thing and differ only in how they react when the requested element was not found.

Answer from Dimitris Fasarakis Hilliard on Stack Overflow
🌐
Sololearn
sololearn.com › en › Discuss › 2343176 › what-is-the-difference-between-rfind-index
What is the difference between rfind() & index()?
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
🌐
W3Schools
w3schools.com › python › ref_string_rindex.asp
Python String rindex() Method
The rindex() method finds the last occurrence of the specified value. The rindex() method raises an exception if the value is not found. The rindex() method is almost the same as the rfind() method.
Top answer
1 of 2
10

Is there any significant difference in term of speed other than potential overheads if we have to enclose s.index() within a try/except.

In (C)Python at least, find, index, rfind, rindex are all wrappers around an internal function any_find_slice.

The implementation is the same. The only difference is that index and rindex will raise a ValueError for you if it finds that the result of calling any_find_slice is -1.

If you went ahead and timed these you'd see how there's clearly no meaningful difference between them:

➜  ~ python -m perf timeit -s "s = 'a' * 1000 + 'b'" "s.find('b')"
Median +- std dev: 399 ns +- 7 ns
➜  ~ python -m perf timeit -s "s = 'a' * 1000 + 'b'" "s.index('b')"
Median +- std dev: 396 ns +- 3 ns

I'm using perf for the timings here.

I'm guessing in other implementations of Python this shouldn't differ. Both methods do the same thing and differ only in how they react when the requested element was not found.

2 of 2
1

@Dimitris's answer showed that s.find() and s.index() perform equally well if the substring is found.

But as @augustomen pointed out, if the substring is not found then s.index() will be significantly slower due to the exception handling. We can test this with the following code snippets.

Note that I'm using a different machine to @Dimitris so my timings cannot be compared with his.

$ python3 -m timeit -s "s = 'a' * 1000" "s.find('b')"
5000000 loops, best of 5: 87.3 nsec per loop
$ python3 -m timeit -s "s = 'a' * 1000" "try: s.index('b')" "except ValueError: pass"
1000000 loops, best of 5: 242 nsec per loop

It's clear that s.find() is the winner when the substring is not found, but is that just because we didn't include a try/except block for it?

Let's try adding a try/except block to s.find() (even though we know it won't be triggered).

$ python3 -m timeit -s "s = 'a' * 1000" "try: s.find('b')" "except ValueError: pass"
5000000 loops, best of 5: 89.1 nsec per loop

We see here that the mere presence of a try/except block barely alters the time at all. It's only when the exception is actually triggered that we incur a meaningful hit to performance.

The moral of the story is to use s.find() if there's a reasonable chance that the substring won't be found.

If you're sure that the substring will almost always be found then you can use either s.find() or s.index(). You might prefer s.index() in that case, because the try/except syntax signals to other developers that you are handling an edge case that you don't expect will occur very often.

🌐
Programiz
programiz.com › python-programming › methods › string › rindex
Python String rindex()
The only difference is that rfind() returns -1 if the substring is not found, whereas rindex() throws an exception. quote = 'Let it be, let it be, let it be' result = quote.rindex('let it') print("Substring 'let it':", result) result = quote.rindex('small') print("Substring 'small ':", result) ...
🌐
Learn By Example
learnbyexample.org › python-string-rfind-method
Python String rfind() Method - Learn By Example
April 20, 2020 - The only difference is that the rindex() method raises a ValueError exception, if the substring is not found. S = 'Big, Bigger, Biggest' x = S.rfind('Small') print(x) # Prints -1
🌐
W3Schools
w3schools.com › python › ref_string_rfind.asp
Python String rfind() Method
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.
🌐
Scaler
scaler.com › home › topics › rfind() in python
rfind() in Python | rfind() Function in Python - Scaler Topics
June 15, 2022 - The only difference between the rfind() method and rindex() method is that if the substring is not found in the given string, rfind() method returns -1, whereas rindex() raises an error. The string rfind() method can also be used to check whether a substring is present in the given string or not.
🌐
datagy
datagy.io › home › python posts › python strings › python rfind: find index of last substring in string
Python rfind: Find Index of Last Substring in String • datagy
December 19, 2022 - You’ll learn how to use the Python .rfind() method, how to use its parameters, how it’s different from .rindex(), and how to use the method to see if a substring only exists once in a string.
Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › python › string_rfind.htm
Python String rfind() Method
The Python String rfind() method ... is found in an original string. Unlike the rindex() method, which raises an exception if the substring is not present, this method returns -1....
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › methods › string › rfind › python-string-rfind
Python rfind() function | Why do we use Python String rfind() function? |
September 27, 2021 - They are used to find out the index value of a specified element from the input string. The only difference between them is that the rindex() method throws a ValueError if the substring cannot be found.
🌐
DEV Community
dev.to › itsmycode › python-string-rfind-23mb
Python String rfind() - DEV Community
January 25, 2022 - The only major difference is that the rfind() method returns -1 if the substring is not found in a given string, whereas the rindex() method will raise the ValueError: substring not found exception.
🌐
Jobtensor
jobtensor.com › Tutorial › Python › en › String-Methods-rindex
Python String rindex(), Definition, Syntax, Parameters, Examples | jobtensor
The rindex() method finds the last occurrence of the specified value. It raises an exception if the value is not found. This method is almost the same as the rfind() method. ... testStr = "Welcome to the Python tutorials. Python is a scripting language." result = testStr.rindex("Python") ...
🌐
Stack Overflow
stackoverflow.com › questions › 73559365 › time-complexity-of-python-rfind
indexing - Time Complexity of Python `rfind()` - Stack Overflow
I agree, you are preforming an O(n) operation with the for loop, and the s.rindex(c) is preforming also an O(n) operation.
🌐
W3Schools
w3schools.com › python › showpython.asp
W3Schools online PYTHON editor
Get your own Python server · Change Orientation Ctrl+Alt+O Change Theme Ctrl+Alt+D Go to Spaces Ctrl+Alt+P · -1 Traceback (most recent call last): File "demo_ref_string_rfind_vs_rindex.py", line 4 in <module> print(txt.rindex("q")) ValueError: substring not found
🌐
Programiz
programiz.com › python-programming › methods › string › rfind
Python String rfind()
The rfind() method returns the highest index of the substring (if found). If not found, it returns -1.
🌐
Programmersought
programmersought.com › article › 82781202681
The difference between find() and rfind() in Python - Programmer Sought
Python rfind() returns the first occurrence of the string (from right to left), or -1 if there is no match.