[Tutor] S.find()
Steven D'Aprano
steve at pearwood.info
Fri Jul 2 01:33:02 CEST 2010
On Fri, 2 Jul 2010 08:05:35 am Corey Richardson wrote:
> Hello Tutors!
> I'm having a problem with the find() method of string objects.
[...]
> The module documentation lists it as this: "S.find(sub[, start[,
> end]]) -> int".
> I'm assuming sub is the string you want to find, and that is how
> it has worked out for me. (Bonus Points: What does sub mean?
"substring"
> I'm
> guessing subscriptable, as one of my errors says, but I'll get to
> that...) When I try gameWord.find('p'[,1[,3]]), as the little help
> box suggests, I get this:
>
> SyntaxError: invalid syntax
There's a skill you need to read documentation. In particular, you need
to know one small fact, without which function signatures like
S.find(sub[, start[, end]]) -> int
are totally mysterious. That is that square brackets [ ] are used to
show optional arguments, and you don't type them! In Python, square
brackets make lists, and the would-be-list [, 1[, [3]] is malformed,
hence the Syntax error.
This shows that the method takes one compulsory argument (sub),
optionally followed by either one optional argument (start) or two
(start and end), and returns an integer result. So the example above is
equivalent to three examples:
S.find(sub) -> int
S.find(sub, start) -> int
S.find(sub, start, end) -> int
Don't forget that indexes in Python start counting from 0, not 1, so
passing 1 as the starting index means you skip the first character.
> Ok then, that is the exact syntax I was given. My next try is, and
>
> gives, this:
> >>> gameWord.find('p', [1,[3]])
>
> Traceback (most recent call last):
> File "<pyshell#99>", line 1, in <module>
> gameWord.find('p', [1,[3]])
> TypeError: slice indices must be integers or None or have an
> __index__ method
Now you use properly formed lists, but the start argument (if given)
can't be a list [1, [3]]. It has to be an integer, or None, or some
object which is convertable to an integer using the __index__ method:
> I assumed the comma after the 1 was messing it up, so I put this:
> >>> gameWord.find("p", [1[3]])
>
> Traceback (most recent call last):
> File "<pyshell#101>", line 1, in <module>
> gameWord.find("p", [1[3]])
> TypeError: 'int' object is not subscriptable
To Python, it looks like you're passing as the start argument a list
containing a single value, which is the 3rd element of the int 1. But
ints don't have elements and so can't be subscripted like 1[3], hence
the error.
--
Steven D'Aprano
More information about the Tutor
mailing list