Another Wart! string.find() [ was: namespace issue? ]

Jeff Shannon jeff at ccvcorp.com
Fri Jun 22 22:56:02 CEST 2001


Michael Powe wrote:

> >>>>> "Steven" == Steven D Majewski <sdm7g at Virginia.EDU> writes:
>
>     Steven> ( But I can't really think of a good reason for
>     Steven> string.find to return -1 *except* that it wouldn't
>     Steven> surprise a C programmer. )
>
> Well, if we had boolean values, it could just return false!  I wonder
> what percentage of the time string.find() is used just as I was using
> it, to check for the existence of a substring rather than actually
> doing something with it when found.  Maybe, we just need the python
> equivalent of strchr() in C (returns a pointer or NULL, i.e., true or
> false).
>
> mp

Except that, even if string.find() returned None (false), it still
wouldn't work:

    s = "spam"
    sub = "sp"
    if string.find(s, sub):
        dospam()

In this case, dospam() never executes, even though our substring *is*
found.

While you *could* explicitly test

    if string.find(s, sub) is not None:

I don't see this as being really any better than

    if string.find(s, sub) >= 0:

or

    if string.find(s, sub) == -1

In other words, it is possible for a valid positive return from
string.find() to still
evaluate to a boolean false... so the idiom that you would like to use is
not
going to work, without doing away with 0-based indexing.  And that would
be a really bad idea, even discounting how much code it would break.
(Alex Martelli has explained in great detail why not too long ago--search

google for "0-based index" or "half-open ranges" for more details)

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list