A regex is probably overkill for this. I'd use in
.
Example 1:
The way I'd implement findphrase()
, given your requirement of returning a 1
or 0
is:
>>> def findphrase(phrase, to_find):
... if to_find.lower() in phrase.lower():
... return 1
... else:
... return 0
...
>>> phrase = "I'm not well today."
>>> to_find = 'not well'
>>> in_phrase = findphrase(phrase, to_find)
>>> assert in_phrase == 1
>>>
Note the use of to_find.lower()
and phrase.lower()
to ensure that capitalization doesn't matter.
Example 2:
But frankly, I'm not sure why you want to return 1 or 0. I'd just return a boolean, which would make this:
>>> def findphrase(phrase, to_find):
... return to_find.lower() in phrase.lower()
...
>>> phrase = "I'm not well today."
>>> to_find = "not well"
>>> in_phrase = findphrase(phrase, to_find)
>>> assert in_phrase == True
>>>
In the event that you truly need to use the results as a 1
or 0
(which you don't if you rewrite your howareyou()
function), True
and False
convert to 1
and 0
, respectively:
>>> assert int(True) == 1
>>> assert int(False) == 0
>>>
Additional Notes
In your howareyou()
function, you've got a number of errors. You're calling findphrase()
as findphrase('not well')(howis)
. That would only work if you're returning a function from findphrase()
(a closure), like so:
>>> def findphrase(var):
... def func(howis):
... return var.lower() in howis.lower()
... return func
...
>>> phrase = "I'm not well today."
>>> to_find = "not well"
>>> in_phrase = findphrase(to_find)(phrase)
>>> assert in_phrase == True
>>>
This works because a function is just another type of object in Python. It can be returned just like any other object. Where you might want to use a construct like this is if you're doing something along these lines:
>>> def findphrase(var):
... def func(howis):
... return var.lower() in howis.lower()
... return func
...
>>> phrases = ["I'm not well today.",
... "Not well at all.",
... "Not well, and you?",]
>>>
>>> not_well = findphrase('not well')
>>>
>>> for phrase in phrases:
... in_phrase = not_well(phrase)
... assert in_phrase == True
...
>>>
This works because you're assigning the results of findphrase('not well')
to the variable not_well
. This returns a function, which you can then call as not_well(phrase)
. When you do this, it compares the variable phrase
that you're providing to not_well()
to the variable var
, which you provided to findphrase()
, and which is stored as part of the namespace of not_well()
.
But in this case, what you'd probably really want to do would be to define your findphrase()
function with two arguments, like one of the first two examples.
You're also using findphrase(...) is 1
. What you probably want there is findphrase(...) == 1
or, even more pythonic, if findphrase(...):
.