Is there a way i can search in a list for some letters of a word and delete the whole word?(SOLVED)

Viewed 20

im trying to code a simple contact book with just names and phone numbers. I want it to have the options add,remove,search and exit obviously. In my remove and search option i got one problem: For example if the use adds a new name to the contact book for example "Alex Balex" and wants to remove it or search it after he needs to type Alex Balex but i want the program to find and delete Alex out of the list if i search for "Alex Bal" aswell. That was my attempt but i cant find a solution:

import pickle import sys while True:

option = int(input(("You got 3 options 1=add 2=remove 3=search 4=exit and save. Please enter what you want to do: ")))
if option == 1:
    names = []
    names = pickle.load(open("names.dat", "rb"))

    new_entry, new_number = str(input("Enter a new name which you want to be added to the CB in this format name:phone_number\nINPUT: ")).split(":")
    new_user = "Name: " + new_entry + "         Number: " + new_number
    names.append(new_user)
    pickle.dump(names, open("names.dat", "wb"))
elif option == 2:
    names = []
    names = pickle.load(open("names.dat", "rb"))
    print(names)
    new_removal = str(input("Enter what you want to remove: "))
    for element in names:
        if new_removal in element:
            names.remove(names[names.index(element)])
    pickle.dump(names, open("names.dat", "wb"))
elif option == 4:
    sys.exit()

elif option == 3:
    names = []
    names = pickle.load(open("names.dat", "rb"))
    print(names)
    new_search = str(input("Search either a name or a number: "))
    for element in names:
        if new_search in element:
            new_search = names[names.index(element)]
            print(new_search)
    pickle.dump(names, open("names.dat", "wb"))
1 Answers

A simple solution to your problem is to find the first name with the prefix the user entered, and then remove that:

elif option == 2:
    new_removal = str(input("Enter what you want to remove: "))
    i_remove = -1
    for i, name in enumerate(names):
        if name.lower()[0:len(new_removal)] == new_removal.lower():
            i_remove = i
            break
    if i_remove != -1:
        names.remove(i_remove)
    else:
        print(f"Name not found: {new_removal}", file=sys.stderr)

One question you'll need to consider though is what to do if multiple names start with the same prefix.

For example, what if a user's contact list contains Alex Balex, and Alex Ball, and the user asks to remove Alex Bal?

The simplest solution here would be to simply not remove anything since the specific name of the contact cannot be deduced - but another option might be instead to prompt the user with the list of contacts with that prefix and ask them to choose which one they want to remove.

I leave this part to you - good luck!

Related