views:

5969

answers:

5

I am trying to find some examples but no luck. Anyone knows some examples on the net? I want to know what it returns when it can't find, and how to specify from start to end, which I guess is gonna be 0, -1.

+5  A: 

I'm not sure what you're looking for, do you mean find()?

>>> x = "Hello World"
>>> x.find('World')
6
>>> x.find('Aloha');
-1
Paolo Bergantino
Thanks, what do you get, if it can't find?
Joan Venge
-1 says my python shell
SilentGhost
You get -1, updated with link to docs and example.
Paolo Bergantino
Thanks, but why -1 here, not for index? I thought python prefers exceptions over special return values.
Joan Venge
@Joan: see my answer
SilentGhost
Thanks SilentGhost, I used your method.
Joan Venge
find and index are the same functionality but with different results on no match. Python might in general prefer exceptions, but many users expect there to be a non-exception-raising-find-index method as well, especially as that's how it's done in almost every other language.
bobince
+5  A: 

you can use str.index too:

>>> 'sdfasdf'.index('cc')
Traceback (most recent call last):
  File "<pyshell#144>", line 1, in <module>
    'sdfasdf'.index('cc')
ValueError: substring not found
>>> 'sdfasdf'.index('df')
1
SilentGhost
Why would you choose one over the other?
endolith
it raises the error instead of returning a code, which is more pythonic, in my opinion.
SilentGhost
exceptions should not be used for flow control. so, only use index() if no match would be abnormal.
Wahnfrieden
@Wahnfrieden: using exception is perfectly pythonic. And certainly doesn't deserve a downvote.
SilentGhost
A: 

find( sub[, start[, end]])

Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

From the docs.

MarkusQ
+3  A: 

Honestly, this is the sort of situation where I just open up Python on the command line and start messing around:

 >>> x = "Dana Larose is playing with find()"
 >>> x.find("Dana")
 0
 >>> x.find("ana")
 1
 >>> x.find("La")
 5
 >>> x.find("La", 6)
 -1

Python's interpreter makes this sort of experimentation easy. (Same goes for other languages with a similar interpreter)

Dana
IPython makes this sort of thing even better.
endolith
+1  A: 

From here:

str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found."

So, some examples:

>>> str = "abcdefioshgoihgs sijsiojs "
>>> str.find('a')
0
>>> str.find('g')
10
>>> str.find('s',11)
15
>>> str.find('s',15)
15
>>> str.find('s',16)
17
>>> str.find('s',11,14)
-1
Phil H
Generally not a good idea to use words like `str` as variable names..
John Fouhy