What is wrong in my list comprehension?

Peter Otten __peter__ at web.de
Mon Feb 2 12:05:09 EST 2009


J Kenneth King wrote:

> Chris Rebert <clp2 at rebertia.com> writes:
> 
>> Python 2.6 (r26:66714, Nov 18 2008, 21:48:52)
>> [GCC 4.0.1 (Apple Inc. build 5484)] on darwin
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>> bool(-1)
>> True
>>
>> str.find() returns -1 on failure (i.e. if the substring is not in the
>> given string).
>> -1 is considered boolean true by Python.
> 
> That's an odd little quirk... never noticed that before.
> 
> I just use regular expressions myself.
> 
> Wouldn't this be something worth cleaning up? It's a little confusing
> for failure to evaluate to boolean true even if the relationship isn't
> direct.

Well, what is your suggested return value when the substring starts at
position 0?

>>> "abcde".find("abc")
0

By the way, there already is a method with a cleaner (I think) interface:

>>> "abcde".index("abc")
0
>>> "abcde".index("cde")
2
>>> "abcde".index("xyz")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

Peter




More information about the Python-list mailing list