Reputation: 23
What I want to do is look for different strings in a string and act differently upon some of them. Ths is what I have now:
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)
I plan to change the "print" at the end to another action later on. So basicly if the user inputs the string "Genisis" then it will take action #1 and if the user inputs "Gen." it will also take action #1 as with all the other forms of the string "Genisis" but if the user inputs the string "Matthew" I want it to take action #2 and it should take action #2 with all the other variations of matthew.
I considered something like this:
book = raw_input("What book do you want to read from today? "
if book == "Genesis":
print "Genesis"
but that would require lots of lines for all the variations I have listed of "genesis"
I hope someone can help!
Upvotes: 3
Views: 48
Reputation: 78554
You can use a for loop and test for the containment of a book in any of a unique set of keywords. Whatever variation the book input takes, str.lower
ensures you can find it in a keyword and take action based on the keyword:
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
Upvotes: 0
Reputation: 12168
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!')
Upvotes: 3
Reputation: 691
Using slices would still require you to write an if
statement, but it would make the reduce the amount of code needed:
if book in keywords[:6]:
print "Genesis"
Upvotes: 1