提问人:Weverson Goncalves Muciarone 提问时间:10/6/2023 最后编辑:CausingUnderflowsEverywhereWeverson Goncalves Muciarone 更新时间:10/6/2023 访问量:52
如何执行不区分大小写的字符串匹配python 3.10?[复制]
How to perform case insensitive string-matching python 3.10? [duplicate]
问:
我正在尝试从 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”、“Add”甚至“ADD”。
答:
1赞
Andrej Kesely
10/6/2023
#1
使用户输入小写(带):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
评论
1赞
Weverson Goncalves Muciarone
10/6/2023
这是伟大的安德烈。修复简单,效率高。非常感谢您的帮助。
评论