0

So I want to be able to print out number of occurances: For example if I have following in my text file:

cheeesepizza

chickenpizza

pepornisub

pizzaaregood

I want to be able to print "There are 2 pizza." ...Here is what I have so far

f = open(file_name)
total = 0
for line in f:
    if "pizza" in line:
        total += 1
f.close()
print total
Community
  • 1
  • 1
John Pro
  • 35
  • 5

1 Answers1

1

You need to check if "pizza" is at the end of the line. The in operator checks if something appears anywhere in a list or string, not just at the end.

We can check if a string ends with something using the endswith bound method on a str. Change your if statement to this:

if line.endswith("pizza"):

Full code:

f = open(file_name)
total = 0
for line in f:
    if line.endswith("pizza"):
        total += 1
f.close()
print total

If you wanted a more Pythonic way to do what you're trying to achieve, use a list comprehension and count the items, like this:

f = open(file_name)
total = len([line for line in f if line.endswith("pizza")])
f.close()
print total
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
  • Can you please help me with a full code that will work? Pleaese please! – John Pro May 16 '16 at 20:00
  • 1
    Ive never understood people who want "full code" ... that indicates this is clearly for a class assignment(and indicates that you have no desire to actually learn how to solve the problem yourself) ... now you do not have the requisite knowledge the lesson was designed to teach ... good luck on the test ... and good luck in a real interview later – Joran Beasley May 16 '16 at 20:03
  • Thanks one more question. how to make the input readable from a input pipe, for instance if i am using command line? – John Pro May 16 '16 at 20:03