.find() Function In Python Isn't Working
Solution 1:
Your boolean and use of .find() are both wrong.
First, if you and together '24' and 'England' you just get 'England':
>>> '24'and'England''England'That is because both strings are True in a Python sense so the right most is the result from and. So when you use s.find('24' and 'England') you are only searching for 'England'
The .find() returns the index of the substring -- -1 if not found which is also True in a Python sense:
>>> bool(-1)
TrueAnd .find() could return the index 0 for a string that starts with the target string yet, in a boolean sense, 0 is False. So in this case you would incorrectly think that string was not found.
The correct operator to test for presence or membership testing in Python is in:
>>>s='I am 24 and live in England'>>>'24'in s and'England'in s
True
You can write your if statement that way, or more idiomatically, to test more than one condition, use all (for and) or any (for or) with in:
>>> all(e in s for e in ('24','England'))
True>>> any(e in s for e in ('France','England'))
True>>> all(e in s for e in ('France','England'))
FalseThen you can seamlessly add conditions in the future rather than change your code.
Solution 2:
Find does not return a boolean, it returns the starting index of the found value. If the value can't be found, it returns -1.
s=raw_input('Please state two facts about yourself')
if s.find('24') >=0and s.find ('England') >= 0:
print'are you Jack Wilshere?'else:
print'are you Thierry Henry?'Solution 3:
You need to use s.count()
or s.find() != -1: on each: England and 24
if s.find('24' and 'England'): # it's a number which is always true hence your code is failing
Post a Comment for ".find() Function In Python Isn't Working"