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
2009-03-23 19:00:13
Thanks, what do you get, if it can't find?
Joan Venge
2009-03-23 19:00:33
-1 says my python shell
SilentGhost
2009-03-23 19:01:41
You get -1, updated with link to docs and example.
Paolo Bergantino
2009-03-23 19:01:42
Thanks, but why -1 here, not for index? I thought python prefers exceptions over special return values.
Joan Venge
2009-03-23 19:02:47
@Joan: see my answer
SilentGhost
2009-03-23 19:03:17
Thanks SilentGhost, I used your method.
Joan Venge
2009-03-23 19:04:14
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
2009-03-23 19:35:38
+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
2009-03-23 19:00:24
it raises the error instead of returning a code, which is more pythonic, in my opinion.
SilentGhost
2009-11-08 11:33:53
exceptions should not be used for flow control. so, only use index() if no match would be abnormal.
Wahnfrieden
2010-07-05 11:19:43
@Wahnfrieden: using exception is perfectly pythonic. And certainly doesn't deserve a downvote.
SilentGhost
2010-07-05 12:44:10
+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
2009-03-23 19:02:04
+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
2009-03-23 19:03:50
Generally not a good idea to use words like `str` as variable names..
John Fouhy
2009-03-23 22:07:20