pythondelimiter

Having an issue while working with an delimiter to convert the user_input to list or set


I want to delete the elements from the main_list and the elements are taken from the user as user_input where all the part of the code executed perfectly but the elements are not deleted from the main_list there are no error messages so I do not know where the problem lied.

the code is-

def convert_input_to_set(user_input, delimiter=None):
    try:
        elements = set(user_input.split(delimiter)) if delimiter else set(user_input.split())
        return {int(element) if element.isdigit() else element for element in elements}
    except Exception as e:
       print(f"\nError: {e}. Make sure you provide a valid list. Let's try this again.\n")
    return set()

def remove_element(main_list):
    while True:
        print("Use comma ',', space ' ', pipe '|', or semicolon ';' to separate the elements.\n")

        user_input = input("Enter the elements you want to remove from the main list: ")
        elements = convert_input_to_set(user_input)
    
        print(f"\nYour elements to remove: {', '.join(map(str, elements))}. Does this look correct?")
        confirmation = input("\nType 'y' or 'yes' to confirm, or 'n' or 'no' to retry: ").lower()
    
        if confirmation in {"yes", "y"}:
            main_list[:] = [element for element in main_list if element not in elements]
            print("\nThe elements have been removed from the main list.\n")
            break
        else:
            print("Okay, let's try again.")
    
    return main_list

main_list = [1, 2, 3, 4, 5, 6]

main_list = remove_element(main_list)

print(main_list)

When I change the approach to convert the user_input into set, where I changed this code elements = set(user_input.split(delimiter)) if delimiter else set(user_input.split()) to this elements = user_input.replace(',', ' ').replace(';', ' ').replace('|', ' ').split() the code ran perfectly. My Question is, What was the issue I was having while running this code elements = set(user_input.split(delimiter)) if delimiter else set(user_input.split())


Solution

  • string.split() doesn't work as you expect.

    If no argument is passed to the split function, the default value None is used, so "hello".split() will return ["hello"] not ['h', 'e', 'l', 'l', 'o']. You should use list(string) for that.

    But, there is another issue in your code. You are building a set from the list while converting digits to integers and keeping the others as they are. For example, if you enter "1|2", it will return {"1", "2", "|"}, which is probably not what you want. You should only add to the set if the character is a digit.

    So you can use this:

    def convert_input_to_set(user_input, delimiter=None):
        try:
            elements = set(user_input.split(delimiter) if delimiter else list(user_input))
            return { int(element) for element in elements if element.isdigit() }
        except Exception as e:
           print(f"\nError: {e}. Make sure you provide a valid list. Let's try this again.\n")
        return set()
    

    Edit:

    If you want to split multiple characters like "apple" or a 2-digit number like 12, you can replace all delimiters with some single delimiter and then split.

    like:

    def convert_input_to_set(user_input, delimiter=' '):
        try:
            for char in [',', '|', ';']:
                user_input = user_input.replace(char, delimiter)
            elements = set(user_input.split(delimiter))
            return { int(element) if element.isdigit() else element for element in elements }
        except Exception as e:
           print(f"\nError: {e}. Make sure you provide a valid list. Let's try this again.\n")
        return set()