[英]Converting txt file to list and returning line after user input search
I'm trying to have the user input a telephone number, then the program will open a text file, convert it to a list, search the list and if the phone number is found it will return the rest of the line (which contains the address for that phone number. 我正在尝试让用户输入电话号码,然后程序将打开一个文本文件,将其转换为列表,搜索列表,如果找到了电话号码,它将返回该行的其余部分(其中包含该电话号码的地址。
I can only get it to return either "phone number not found" or the line but it does it for every single line so I end up with an output like this: 我只能让它返回“找不到电话号码”或该行,但是它对每一行都执行此操作,因此最终得到这样的输出:
phone number not found
phone number not found
0121 254132 18 Springfield Road
phone number not found
phone number not found
for line in phonenumbers:
if number in line:
print (line)
else:
print ("phone number not found")
I know it's because I've put for line in phonenumbers but don't know how to not do it for every line. 我知道这是因为我已经在电话号码中加入了行号,但不知道如何不对每一条线都这样做。
try the following: 尝试以下方法:
for line in phonenumbers:
if number in line:
print (line)
break
else:
print ("phone number not found")
the else
is part of the for
loop and will only execute if you didn't break
out of the for
loop. 在else
的部分for
循环,如果你没有将只执行break
了的for
循环。
Why do you not just drop the else statement. 您为什么不只删除else语句。 It should look something like: 它看起来应该像这样:
for line in phoneNumbers:
if phone in line:
print line
If you want a result in case that it was not found you could use a flag. 如果希望得到结果,以防找不到,可以使用标志。 moreover you can just use: 此外,您可以使用:
print [line for line in phonenumbers if number in line]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.