are these two statements eq开发者_如何学编程uivalent?
if row[1].upper().find(brand)!=-1:
and
if row[1].upper().find(brand):
No, they aren't equal. In Python, any nonzero number is treated as being True, so the second statement will be considered true if the expression evaluates to -1, and false if the expression evaluates to 0 (when it should be true).
Use the first statement.
As others have said, no those statements are not equivalent. However, when you only need to find if the substring exists and not where, I prefer the in
operator rather than .find()
, e.g.:
if brand in row[1].upper():
This is equivalent to the first statement, but more concise and easy to read.
No.
The first one will evaluate to false
only if find()
returns -1
.
The second one will evaluate to false
only if find()
returns 0
.
This even would give you wrong results as 0
means that the substring was found at the beginning of the string. So this statement would evaluate to false
if the substring is at the beginning and true
if it was not found.
To explain what the find()
method does:
>>> "hello".find("l")
2
>>> "hello".find("he")
0
>>> "hello".find("x")
-1
-1
is a "magic value" for "search string not found". Contrast this with index()
:
>>> "hello".index("l")
2
>>> "hello".index("he")
0
>>> "hello".index("x")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
Personally, I prefer index()
because usually, magic values are frowned upon in Python whereas exception handling is the Pythonic way to do it - "EAFP" (it's easier to ask forgiveness than permission).
In your case it looks like the "LBYL" programming style (look before you leap), although you're not showing much context so I don't know what the if
statement is deciding.
No, of course not.
The first one checks if the result is -1
and the other one checks if the result is anything which Python regards as "false". -1
is not regarded as false by Python.
The top answer is correct. But I find it easier to read in
than to use numeric results. I.e.,
>>> row
[[1, 'lysol']]
>>> brand
'Lysol'
>>> brand.upper() in row[0][1].upper()
True
>>>
Although, once the "Schlysol" brand shows up, all bets are off. Hm.
精彩评论