Python: if string [1] .upper (). find (brand)! = - 1:

- are these two statements equivalent?

if row[1].upper().find(brand)!=-1:

and

if row[1].upper().find(brand):
+3
source share
6 answers

No, they are not equal. In Python, any nonzero number is considered 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.

+8
source

As others have said, none of these statements are equivalent. However, when you need to find only a substring, and not where, I prefer the operator inrather than .find(), for example:

if brand in row[1].upper():

, .

+5

.

false, find() -1.

false, find() 0.
, 0 , . false, true, .

+2

, find():

>>> "hello".find("l")
2
>>> "hello".find("he")
0
>>> "hello".find("x")
-1

-1 " " " ". 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

index(), , , Python , - Pythonic - "EAFP" ( , ).

"LBYL" ( , ), , , if.

+2

, , .

, -1, , , Python "". -1 Python .

+1

The top answer is correct. But it’s easier for me to read inthan to use numerical results. I.e.

>>> row
[[1, 'lysol']]
>>> brand
'Lysol'
>>> brand.upper() in row[0][1].upper()
True
>>> 

Although, as soon as the Schlysol brand appears, all bets are off. Hm.

+1
source

Source: https://habr.com/ru/post/1757164/


All Articles