user1861051 user1861051 - 5 days ago 6
Python Question

Segment of string does not work in "if" statement

I am working on a piece of a program in which I need to search for a string within a text file and print out the line that it is found in. I am having a problem with the following line:

if ingredient[8:] in line :


Nothing ends up being printed out, unless I manually type in the string that is held in ingredient[8:]. For example:

if "tomato" in line :


This works perfectly. I can't seem to figure out why "tomato" or "lentil" would work instead of "ingredient[8:]".

The following is my code:

# VARIABLES
shoppingList=[]

# MOVE CONTENTS OF SHOPPING LIST FILE ONTO LIST
with open("Recipe Shopping List.txt") as f:
content = f.readlines()

def findRecipe():

# PROMPT USER FOR RECIPE NAME
print "Enter a recipe name: "
recipeInput = raw_input()
recipeIndex = content.index(" - " + recipeInput + "\n")

# PUT INGREDIENTS INTO SHOPPING LIST
for ingredient in content[recipeIndex+1:]:
if ingredient.startswith(" -"):
# FIND INGREDIENT'S CATEGORY IN CATEGORY FILE
with open("Ingredient Category List.txt") as categoryFile :
for line in categoryFile :
if ingredient[8:] in line :
print line
else:
break

findRecipe()


And here is the text stored in the test text files:

"Ingredient Category List.txt"

tomato - produce
carrot - produce
celery - produce
lentil - grains


"Recipe Shopping List.txt"

- Lentil soup
- 2 lentil
- 3 tomato
- 4 celery
- 4 carrot
- Gnocchi
- 1 tomato
- 3 gnocchi
- 2 onion


Thank you in advance for any help.

Answer

ingredient[8:] includes the line feed. Chop it one character short:

if ingredient[8:-1] in line:

Better yet, split the line and pull out the one field you need, nicely stripped of white space.

Comments