我正在處理一段程序,該程序需要在文本文件中搜索字符串並打印出它所在的行。我正在正在打印字符串段在「if」語句中不起作用
if ingredient[8:] in line :
沒有結束時,除非我手動鍵入在被在成分保持的字符串:使用以下行的問題[8:]。例如:
if "tomato" in line :
這很好。我似乎無法弄清楚爲什麼「番茄」或「小扁豆」可以代替「成分[8:]」。
以下是我的代碼:
# 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()
,這裏是存儲在測試文本文件的文本:
「成分分類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
非常感謝您的幫助。
@leaf感謝您的回覆。 '成分'應該保存像「-2扁豆」這樣的字符串,所以我試圖引用僅包含食物名稱的子字符串,所以在這種情況下我認爲「成分[8:]」只是「扁豆」 。當我打印'成分[8:]'時,我確實得到了「小扁豆」並且是str型。 – user1861051
我的不好。我剛剛意識到我的錯誤。我會刪除我的評論。 –