如何执行不区分大小写的字符串匹配python 3.10?

问题描述 投票:0回答:1

我正在尝试从 python 版本 3.10+ 运行 case 语句,其中用户应键入单词“add”作为输入。但是,如果用户使用大写字母(如“Add”),则不起作用。

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')

我尝试在匹配用户中使用方法

capitalize()
,但这不起作用。我可以使用 case 'add' | “添加”,但我正在尝试找到一个可靠的解决方案。

我希望用户能够从 case 语句中输入单词,例如“添加”、“添加”甚至“添加”。

python string match case-insensitive
1个回答
0
投票

将用户的输入设为小写(使用

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

打印(例如):

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
© www.soinside.com 2019 - 2024. All rights reserved.