将用户输入与已知字符串进行比较
Compare user input to known string
我正在尝试将用户提供的单词(例如 "orange"
)与文本文件中的单词列表进行比较,如下所示:
menu.txt
apple
banana
orange
grape
mango
用户输入来自easygui.enterbox
。我从来没有得到我期望的结果,因为它很难比较字符串。这是我的代码。
import easygui
count = 0
dish = easygui.enterbox("enter your favourite dish:")
with open("menu.txt") as f:
content = f.readlines()
for item1 in content:
if item1 == dish :
easygui.msgbox("order taken.thankyou")
count = count + 1
continue
if count == 0 :
easygui.msgbox("plz order some other item")
首先你不需要 readlines()
遍历你的行,其次你需要 strip
你的行再比较!因为那些包含换行符 \n
!
import easygui
count = 0
dish = easygui.enterbox("enter your favourite dish:")
with open("menu.txt") as f:
for item1 in f:
if item1.strip() == dish :
easygui.msgbox("order taken.thankyou")
count = count + 1
continue
if count == 0 :
easygui.msgbox("plz order some other item")
f.readlines()
returns 带有行尾的项目。你想要 .strip()
换行符和额外的空格。有 else:
for for
循环;你想在这里使用它;如果找到匹配你 break
退出循环; else
报错。另外,缩进4个空格,这是标准。
import easygui
dish = easygui.enterbox("enter your favourite dish:")
with open("menu.txt") as f:
content = f.readlines()
for item1 in content:
item1 = item1.strip()
if item1 == dish:
easygui.msgbox("order taken. thankyou")
# it can match 1 dish only; so we can exit now
break
else:
easygui.msgbox("plz order some other item")
您可能需要向 item 和 dish 添加 .strip() 以确保所有空格或行尾符号都不是字符串的一部分
我正在尝试将用户提供的单词(例如 "orange"
)与文本文件中的单词列表进行比较,如下所示:
menu.txt
apple
banana
orange
grape
mango
用户输入来自easygui.enterbox
。我从来没有得到我期望的结果,因为它很难比较字符串。这是我的代码。
import easygui
count = 0
dish = easygui.enterbox("enter your favourite dish:")
with open("menu.txt") as f:
content = f.readlines()
for item1 in content:
if item1 == dish :
easygui.msgbox("order taken.thankyou")
count = count + 1
continue
if count == 0 :
easygui.msgbox("plz order some other item")
首先你不需要 readlines()
遍历你的行,其次你需要 strip
你的行再比较!因为那些包含换行符 \n
!
import easygui
count = 0
dish = easygui.enterbox("enter your favourite dish:")
with open("menu.txt") as f:
for item1 in f:
if item1.strip() == dish :
easygui.msgbox("order taken.thankyou")
count = count + 1
continue
if count == 0 :
easygui.msgbox("plz order some other item")
f.readlines()
returns 带有行尾的项目。你想要 .strip()
换行符和额外的空格。有 else:
for for
循环;你想在这里使用它;如果找到匹配你 break
退出循环; else
报错。另外,缩进4个空格,这是标准。
import easygui
dish = easygui.enterbox("enter your favourite dish:")
with open("menu.txt") as f:
content = f.readlines()
for item1 in content:
item1 = item1.strip()
if item1 == dish:
easygui.msgbox("order taken. thankyou")
# it can match 1 dish only; so we can exit now
break
else:
easygui.msgbox("plz order some other item")
您可能需要向 item 和 dish 添加 .strip() 以确保所有空格或行尾符号都不是字符串的一部分