如何在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')

我尝试在匹配用户中使用大写()方法,但没有成功。我可以使用 case 'add' | “添加”,但我正在尝试找到一个可靠的解决方案。

我希望用户从 case 语句中键入单词,无论是否区分大小写,是 add、Add 甚至 ADD。

python string match case-sensitive
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.