18_Search_for_field_return_next_column's_field.py


Sign up Free. Don't forget to check out our challenges, lessons, solve and learn series and more ...


Code Snippet

#Search for a teacher, and return the subject they teach
"""File contents
Mr Moose : Maths
Mr Goose: History
Mrs Cook: English

"""

alldata=[]
col_num=0
teacher_names=[]
delimiter=":"

def main():
      with open("teacherbook.txt") as f:
            for line in f.readlines():
                  alldata.append((line.strip()))
            print(alldata)
                    

            print()
            print()

            
      #One alternative is to convert the list into a dictionary, whcih works because it is naturally a key value pair
      teacher_dict=dict(tuple(map(str.strip, x.split(":"))) for x in alldata)
      

      teacher=input("Enter teacher you are looking for:")
      print("The subject is:", teacher_dict[teacher])
            

main()

"""


str.split returns a new list.

for element in l:
    parts = element.split(',')
    print parts
"""
                    

Try it yourself