#πŸ”’ Understanding the difference between index & find method

21 messages Β· Page 1 of 1 (latest)

small marten
#

What's the difference between the .index and .find string method? As far I've learned I can use index with [start:end:step] Can't we just use the .find string method in the image?

narrow groveBOT
#

@small marten

Python help channel opened

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.

sick flicker
#

!d str.index

narrow groveBOT
#

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.
sick flicker
#

!d str.find

narrow groveBOT
#

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
near spindle
#

str.index and str.find seem to do the same thing.

#

Aha, the value error.

sick flicker
#

!e py text = 'abc' print(text.find('d'))

narrow groveBOT
sick flicker
#

!e py text = 'abc' text.index('d')

narrow groveBOT
sick flicker
#

I dislike str.find.

near spindle
#

It's handy for for-loops: while str.find(..) >= 0 do thing, advance

#

Sorry, while loops and similar.

sick flicker
#

"Hey, Python, where is 'd' in 'abc'? Oh, it's where 'c' is? Okay, cool."

near spindle
#

You're conflating "index out of range" with "Python negative list indices". They are different ideas.

sick flicker
#

Allow me my spite.

near spindle
#

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.

narrow groveBOT
#
Python help channel closed

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.