How to perform case insensitive string-matching python 3.10?

71 Views Asked by At

I am trying to run a case statement from python version 3.10+ where a user should type the word 'add' as an input. However, if the user uses a capital letter like 'Add', it does not work.

todos = []

while True:
    user = input('Enter add, show, edit, complete or exit to finish. : ')
    user = user.strip() # This will change the string teh user typed and remove extra spaces

    match user:
        case 'add':
            todo = input('Add an item: ')
            todos.append(todo)
        case 'show' | 'display':
            for i, item in enumerate(todos):
                item = item.title()  # This will make all first letters capitalized
                print(f'{i + 1}-{item}\n')
                list_lengh = len(todos)
            print(f'You have {list_lengh} item in your to do list.\n')

I tried using the method capitalize() in the match user, but that didn't work. I could use case 'add' | 'Add' but I am trying to find a robust solution.

I expect the user to be able to type the word from the case statement, e.g. 'add', 'Add' or even 'ADD'.

1

There are 1 best solutions below

1
Andrej Kesely On

Make the input from the user lowercase (with str.lower):

todos = []

while True:
    user = input("Enter add, show, edit, complete or exit to finish. : ")
    user = user.strip().lower()  # <-- put .lower() here

    match user:
        case "add":
            todo = input("Add an item: ")
            todos.append(todo)
        case "show" | "display":
            for i, item in enumerate(todos):
                item = item.title()  # This will make all first letters capitalized
                print(f"{i + 1}-{item}\n")
                list_lengh = len(todos)
            print(f"You have {list_lengh} item in your to do list.\n")
        case "exit":
            break

Prints (for example):

Enter add, show, edit, complete or exit to finish. : Add
Add an item: Apple
Enter add, show, edit, complete or exit to finish. : show
1-Apple

You have 1 item in your to do list.

Enter add, show, edit, complete or exit to finish. : exit