If I have strings like following:
my_string(0) = Your FUTURE looks good.
my_string(1) = your future doesn't look good.
I want to print both the lines with the following:
for stings in my_string:
if 'FUTURE' or 'future' in string:
print 'Success!'
my if loop works for the first condition with FUTURE, however, the second comparison with future doesn't work. What is the reason?
use:
if 'FUTURE' in string or 'future' in string:
or simply:
if 'future' in string.lower()
Why this failed:
if 'FUTURE' or 'future' in string:
is actually equivalent to :
True or ('future' in string) # bool('FUTURE') --> True
as the first condition is always True so the next condition is never checked .In fact your if-condition is always True no matter what string contains.
A non-empty string is always True in python and or operation short-circuits as soon as a True value is found.
>>> strs1 = "your future doesn't look good."
>>> strs2 = "Your FUTURE looks good."
>>> 'FUTURE' or 'future' in strs1
'FUTURE'
>>> 'Foobar' or 'future' in strs1
'Foobar'
>>> 'Foobar' or 'cat' in strs1
'Foobar'
>>> '' or 'cat' in strs1 # empty string is a falsey value,
False # so now it checks the next condition
Note that :
>>> 'FUTURE' in 'FOOFUTURE'
True
is True, as in operator looks for sub-strings not exact word match.
Use either regex or str.split to handle such cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With