【发布时间】:2021-11-23 11:49:28
【问题描述】:
我在尝试使用用户输入从文本文件中打印出某些元素时遇到了一些困难。
我有一个文本文件,其中分别显示 ID 号、目的地名称、票价和可用座位数,如下所示:
- Z5, 墨尔本, 150, 30
- Z6, 纽约, 120, 60
- Z9, 首尔, 100, 50
- Z2, 东京, 170, 40
我想要用户输入 ID 号或目的地名称,程序将显示 (1) 对应的目的地(如果使用了 ID 号)或重复 (2 ) 目的地名称(如果使用了目的地名称)。
也就是说,用户输入 Z6,程序将显示 New York,或者如果用户输入 New York,则将再次打印 New York。
下面的代码可以打印出ID号对应的目的地;但是,如果用户输入目的地的名称,我似乎无法打印出目的地的名称,因为我得到一个列表索引超出范围错误。
search = str (input ('Please enter the name or ID number of the destination:\n'))
info = open ('destinations.txt', 'r').readlines()
for I in info:
data = I.split (',')
if search == data[0]:
print (data[1])
elif search == data[1]:
print ([data[1])
【问题讨论】:
标签: python list file search text