Result - . find() - Different from expected

Asked

Viewed 39 times

0

When I spin that code:

fname = input('File name: ')
fhand = open(fname)
count = 0
for line in fhand:
    if line.find('Subject:'):
        count = count + 1
print('There were', count, 'subjects lines in ', fname)

With input: mbox-short.txt (Link below)
Correct output: 27 Recent Output: 1883

I have no idea why.
txt file link
py version: 3.8.3 - I don’t even know why I’m using this version, if you have any opinion about it please comment

  • As for the version of Python: 3.8.3 is very current, and is indicated to use. A few days ago came out version 3.9.0 - when you want, and especially if you are going to start a new project, you can upgrade to the 3.9 series

1 answer

3


The method str.find returns the position of the first occurrence of the desired string or -1 when not found.

The main problem is that you just did if line.find('Subject:'). When not found, the return is -1, which is evaluated as True in Python. Only the zero number is evaluated as False. That is, for all rows that it does not find the string will count in its variable; and if it does, but it is at the beginning, the return will be 0 and it will not count.

Just then correct your condition to:

if line.find('Subject:') >= 0:
    count = count + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.