# Slice string based on dictionary membership

First, I have two dictionaries. Suppose one is of teachers and another is of students. Values are IDs. teachers = {"TEACH1": 190010, "TEACH2": 191034, ...} students = {"STUD1": 200035, "STUD2": 203046, ...} [Note that, for demonstration purposes, no name repeats. In other words, teachers and students are mutually unique.] Now, a string comes in after every period at this school. Suppose: "TEACH1 STUD2 STUD7 STUD6 TEACH2 STUD3 STUD4 STUD6". (Once again, please be patient. For online classes, a student can be in multiple classes simultaneously.) So, the task is to make the string neater. For example: string_list=["TEACH1 STUD2 STUD7 STUD6", "TEACH2 STUD3 STUD4 STUD6"] The assumed best practice is string.split() and for, if-statements. • A slice starts from a teacher. • A slice ends with a student. • A slice may contain a teacher and zero students (everyone bunked the class), but never no teacher and some students. • A slice always ends before the next teacher or the end of the string. Comment for more context.

12/1/2020 6:56:45 PM

Md. Niamul Ahad Chowdhury2 Answers

New Answerhello! heres my solution:: g = [] a = string_list.split(" ") for x in a: if x in teachers or x in students: g.append(x) g = " ".join(g) def neat(a): g = a.split("teach") for x in g: if len(x) >= 1: yield "teach" + x.strip(" ") b = (list(neat(g))) print(b)