Reputation: 35
I have encountered the following codes in one of the book and both codes are yielding the same output mentioned below. I understood the 2nd code, however, I am unable to understand the first code specifically this particular line of code i.e., "if line.find('From:') >= 0:
" - I mean what does this line mean by? Is it implying if the line is greater than zero then produce the required result or is it talking about the length function but if its taking length function, then why didn't the author use len(function) of python? And why there is both greater than and equality symbol? I am also getting the same output if I use this line of code i.e., "if line.find('From:') == 0:
". What does this all mean? Can somebody please help me understand this. Would appreciate any help.
# 1st code
import re
hand = open('mbox-short.txt')
for line in hand:
line = line.rstrip()
if line.find('From:') >= 0: # This is also working ---> if line.find('From:') == 0: (BUT WHY and HOW COME)?
print(line)
# 2nd code
hand = open('mbox-short.txt')
for line in hand:
line = line.rstrip()
if line.find('From:'): continue
print(line)
Output:
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
From: [email protected]
Upvotes: 0
Views: 251
Reputation: 61
The function find returns the index of the searched string in given string, and -1 if what is being searched is not found, that is the reason behind the >= 0 clause.
Upvotes: 0
Reputation: 83
the find method checks the string you are calling it on for the first occurence of the substring you pass.
So in your case, it checks the line for the first 'From:' it finds in the line.
If it has a result, then it returns the lowest index of the occurence.
But when there is no result for the search, find() returns -1.
(see Python Doc)
From: [email protected]
has 'From:' at the beginning, so the result index is 0.
if line.find('From:') >= 0:
checks, that there is ANY finding.
On the other hand == 0
would check, that the substring 'From:' is at the beginning of the line
Upvotes: 1