0

Python - What does setting the find() method to -1 mean?

zzz = 'Saitama is a hero' def f(a): if a.find('hero') == -1: # What does == -1 mean here? print('found') f(zzz) Does it mean finding the specified value's reverse? Or does it mean "if there is the absence of the specified value" ? How come "found" is printed when I delete 'hero' from zzz?

6th Oct 2020, 3:53 AM
Solus
Solus - avatar
7 Antworten
+ 1
-1 means not found write this to find output if the condtion didn't achive zzz = 'Saitama is a hero' def f(a): if a.find('hero') == -1: # What does == -1 mean here? print('found') else: print("gggg") f(zzz)
6th Oct 2020, 3:58 AM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 1
U should write any sentence if the condition equal false to execute it and i u don't put else stament u will have output "no output" as the condition equal false And u should use the ready function find like the next not like u do zzz = 'Saitama is sleeping' def f(a): if a.find('hero')== True: print('found') else: print ("Mhmd") f(zzz) Solus
6th Oct 2020, 4:11 AM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 1
No , what is the benifit or object from the single qutation
6th Oct 2020, 4:24 AM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 1
find() method returns the index of the given argument in the calling string object. If the calling string object contains the given argument, the index is returned, but otherwise -1 is returned (indices are positive numbers only - including 0). "Wonder why this also prints 'found':" zzz = 'Saitama is sleeping' def f(a): if a.find('hero'): print('found') f(zzz) 'hero' is not a substring of <zzz>, so -1 is returned. But also remember that Python considers a non zero value to be true, logically. So `if a.find('hero'):` is pretty much `if -1:` which evaluates to true.
6th Oct 2020, 4:43 AM
Ipang
0
Muhammad So basically "if the specified value is NOT found"
6th Oct 2020, 4:01 AM
Solus
Solus - avatar
0
Wonder why this also prints found: zzz = 'Saitama is sleeping' def f(a): if a.find('hero'): <------- shouldn't this be false? print('found') f(zzz)
6th Oct 2020, 4:03 AM
Solus
Solus - avatar
0
I see, so we need a ' == True ' between the find() method and the colon.
6th Oct 2020, 4:16 AM
Solus
Solus - avatar