#π Understanding the difference between index & find method
21 messages Β· Page 1 of 1 (latest)
@small marten
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
!d str.index
str.index(sub[, start[, end]])```
Like [`find()`](https://docs.python.org/3/library/stdtypes.html#str.find), but raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) when the substring is not found.
!d str.find
str.find(sub[, start[, end]])```
Return the lowest index in the string where substring *sub* is found within the slice `s[start:end]`. Optional arguments *start* and *end* are interpreted as in slice notation. Return `-1` if *sub* is not found.
Note
The [`find()`](https://docs.python.org/3/library/stdtypes.html#str.find) method should be used only if you need to know the position of *sub*. To check if *sub* is a substring or not, use the [`in`](https://docs.python.org/3/reference/expressions.html#in) operator:
```py
>>> 'Py' in 'Python'
True
!e py text = 'abc' print(text.find('d'))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
-1
!e py text = 'abc' text.index('d')
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | text.index('d')
004 | ValueError: substring not found
I dislike str.find.
It's handy for for-loops: while str.find(..) >= 0 do thing, advance
Sorry, while loops and similar.
"Hey, Python, where is 'd' in 'abc'? Oh, it's where 'c' is? Okay, cool."
You're conflating "index out of range" with "Python negative list indices". They are different ideas.
Allow me my spite.
These methods are from the Dawn Times, and APIs more closely resembled C. Where a -1 is a common return value for not-found/invalid.
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.