shouldn't 'string'.find('ugh') return 0, not -1 ?

J

jelle

the subject pretty much says it all.
if I check a string for for a substring, and this substring isn't found,
should't the .find method return 0 rather than -1?
this breaks the

if check.find('something'):
do(somethingElse)

idiom, which is a bit of a pity I think.

cheers,

-jelle
 
H

Hrvoje Niksic

jelle said:
the subject pretty much says it all.
if I check a string for for a substring, and this substring isn't found,
should't the .find method return 0 rather than -1?

How would you treat the case of 'something' being at the beginning of
the string? After all, find returns the index.
this breaks the

if check.find('something'):
do(somethingElse)

idiom, which is a bit of a pity I think.

if 'something' in check:
do(somethingElse)
 
M

Marc 'BlackJack' Rintsch

if I check a string for for a substring, and this substring isn't found,
should't the .find method return 0 rather than -1?
this breaks the

if check.find('something'):
do(somethingElse)

idiom, which is a bit of a pity I think.

And what should ``'string'.find('str')`` return? How do you distinguish
the not found at all case from the found at the very beginning case!?

The simple test you want can be written this way:

if 'something' in check:
do(something_else)

Ciao,
Marc 'BlackJack' Rintsch
 
C

Carl Banks

the subject pretty much says it all.
if I check a string for for a substring, and this substring isn't found,
should't the .find method return 0 rather than -1?
this breaks the

if check.find('something'):
do(somethingElse)

idiom, which is a bit of a pity I think.

string.find has always been kind of a wart in Python; that's why
they're getting rid of it. For testing for the presence of a
substring, use the in operator:

if "something" in check:
do(somethingElse)

When you need the position of a substring, using the index methods:

i = check.index("something")

index returns an exception of the substring is not there, so no need
to worry about what it returns.

Finally, it really won't kill you to do this:

if check.find("something") >= 0:
do(somethingElse)


Carl Banks
 
T

TheFlyingDutchman

string.find has always been kind of a wart in Python; that's why
they're getting rid of it. For testing for the presence of a
substring, use the in operator:


Per the Python 3000 presentation given by Guido Van Rossum at
PyCon February 2007, the new Bytes type will have a "wart".

"Has some string-like methods, e.g. .find()"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,538
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top