3

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!

Jakewade09
  • 23
  • 6

3 Answers3

3
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!')
宏杰李
  • 11,820
  • 2
  • 28
  • 35
1

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"
Pike D.
  • 671
  • 2
  • 11
  • 30
  • Yes, [Here is a post](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) that goes more in depth about slices. – Pike D. Jan 12 '17 at 05:29
  • 1
    This would have done the job, but I didn't know anything about slices and how to make it look after string #6 and someone else posted an answer that worked before I saw your response to my question which I accidentally deleted. So I used that one but this one would have worked fine. Thanks for responding so quick. – Jakewade09 Jan 12 '17 at 05:55
0

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
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139