如何在一个字符串中测试不同的字符串,并对其中一些字符串执行不同的操作?Python

2024-05-17 03:42:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做的是在一个字符串中寻找不同的字符串,并对其中一些字符串执行不同的操作。这就是我现在所拥有的:

import re

book = raw_input("What book do you want to read from today? ")
keywords = ["Genesis", "genesis", "Gen", "Gen.", "gen", "gen.", "Matthew", "matthew", "Matt", "Matt.", "matt", "matt." ]
if any(keyword in book for keyword in keywords):
    print("You chose the book of: " + book)

我打算把结尾的“print”改成以后的另一个动作。所以基本上,如果用户输入字符串“Genisis”,那么它将执行操作1,如果用户输入“Gen”,它也将执行操作1,就像所有其他形式的字符串“Genisis”一样,但是如果用户输入字符串“Matthew”,我希望它执行操作2,并且它应该执行操作2和Matthew的所有其他变体

我考虑过这样的事情:

book = raw_input("What book do you want to read from today? "
if book == "Genesis":
    print "Genesis"

但这需要我列出的“创世记”的所有变体都有很多行

希望有人能帮忙


Tags: to字符串用户yougenesisreadinputraw
3条回答

您可以使用for循环和测试将一本书包含在任何一组唯一的关键字中。无论图书输入采用何种变体,str.lower确保您可以在关键字中找到它,并根据关键字执行操作:

actions = {...} # dictionary of functions
keywords = ['genesis', 'matthew', ...]

book = raw_input("What book do you want to read from today? ")

for kw in keywords:
    if book.lower() in kw:
         actions[kw]() # take action!
         break         # stop iteration

使用slices仍然需要编写if语句,但这会减少所需的代码量:

if book in keywords[:6]:
    print "Genesis"
book = raw_input("What book do you want to read from today? ").lower().strip('.')
# keywords = ["Genesis", "genesis", "Gen", "Gen.", "gen", "gen.", "Matthew", "matthew", "Matt", "Matt.", "matt", "matt." ]
if book == 'genesis':
    #action1
    pass
elif book == 'gen':
    #action2
    pass
else:
    print('not find the book!')

相关问题 更多 >