在搜索python文件时,如果没有找到结果,我需要能够打印“无结果”
float
答案 0 :(得分:3)
**strong text**elif x.upper()=="Y":
k=input("Enter the 1st letter of the name (upper-Case):")
y=open("Names.txt","r")
found = False
for i in y.readlines():
if k.upper() in i:
print (i[:-1])
found = True
if not found:
print("no results")
答案 1 :(得分:0)
**strong text**elif x.upper()=="Y":
k=input("Enter the 1st letter of the name (upper-Case):")
y=open("Names.txt","r")
all_lines = y.readlines()
for i in all_lines:
if k.upper() in i:
print (i[:-1])
#need option if no search results are found
found_f = k.upper() in ''.join(all_lines)
您可以一次搜索整个文件。不是最好的表现,但足够简单。那是试图尽量减少对代码的更改。我愿意:
**strong text**elif x.upper()=="Y":
k=input("Enter the 1st letter of the name (upper-Case):")
y=open("Names.txt","r")
all_text = y.read()
for i in all_text.splitlines():
if k.upper() in i:
print (i) # don't need [:-1] anymore
#need option if no search results are found
found_f = k.upper() in all_text