Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何测试一个字符串中的不同字符串,并对其中一些字符串采取不同的操作?python_Python_String_Python 2.7 - Fatal编程技术网

如何测试一个字符串中的不同字符串,并对其中一些字符串采取不同的操作?python

如何测试一个字符串中的不同字符串,并对其中一些字符串采取不同的操作?python,python,string,python-2.7,Python,String,Python 2.7,我想做的是在一个字符串中寻找不同的字符串,并对其中一些字符串采取不同的操作。这就是我现在拥有的: 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

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

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)
我计划稍后将最后的“打印”更改为另一个操作。因此,基本上,如果用户输入字符串“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"
但这需要我列出的《创世纪》的所有变体有很多行


我希望有人能帮忙

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

if book in keywords[:6]:
    print "Genesis"

您可以使用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

是的,这是关于切片的更深入的内容。这本可以完成工作,但我对切片以及如何让它照顾string#6一无所知,在我看到你对我的问题的回答之前,其他人发布了一个有效的答案,我不小心删除了我的问题。所以我用了那个,但这个很好用。谢谢你这么快的回复。
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