Python Forum
Why isn't this code working?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why isn't this code working?
#1
I am a beginner.

The following code prints out lines that begin with From:.

fhand = open('mbox-short.txt')
for line in fhand:
     line = line.rstrip()
     if line (startswith('From:') :
         print(line)
However, this line, which is supposed to only print lines containing the word Horwitz, prints every single line in the file. Why?

If I'm using the wrong term to find a string, what is the correct one?

fhand = open('mbox-short.txt')
for line in fhand :
     if line.find('horwitz') :
          print(line)
Thanks!

Yours,
Dora Smith
Reply
#2
Use if line.find('horwitz') != -1: or better if 'horwitz' in line:.
Reply
#3
its not working because, find() method returns the lowest index of the substring if it is found in given string. If its is not found then it returns -1.

>>> x='012345horwitz678910'
>>> x.find('horwitz')
6
>>> x.find('XXX')
-1
>>> 'horwitz' in x
True
>>> 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  New to Python - Not sure why this code isn't working - Any help appreciated TheGreatNinx 4 910 Jul-22-2023, 10:21 PM
Last Post: Pedroski55
  code not working when executed from flask app ThomasDC 1 838 Jul-18-2023, 07:16 AM
Last Post: ThomasDC
  I am new to python and Could someone please explain how this below code is working? kartheekdas 2 980 Dec-19-2022, 05:24 PM
Last Post: kartheekdas
Exclamation My code is not working as I expected and I don't know why! Marinho 4 1,031 Oct-13-2022, 08:09 PM
Last Post: deanhystad
  My Code isn't working... End3r 4 1,867 Mar-21-2022, 10:12 AM
Last Post: End3r
  I don't undestand why my code isn't working. RuyCab 2 1,956 Jun-17-2021, 03:06 PM
Last Post: RuyCab
  code is not working , can anybody help? RandomPerson69 4 2,850 Mar-22-2021, 04:24 PM
Last Post: deanhystad
  Short code for EventGhost not working Patricia 8 3,587 Feb-09-2021, 07:49 PM
Last Post: Patricia
  Code no longer working yk303 14 9,955 Dec-21-2020, 10:58 PM
Last Post: bowlofred
  autocomplete working code sample not working... aviper4u 0 1,603 Oct-24-2020, 03:04 AM
Last Post: aviper4u

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020