-1

I'm trying to match the output of a re.search against a list and run code if the IF statement allows. However, even if I tell the IF statement to match True or False, the IF statement never proceeds.

Running the search in python:

>>> re.search(r'...$', 'abcde1234doc').group() in ['doc', 'rtf', 'txt']
>>> True

Returns True, so by asking the IF statement to match True, it should proceed with it's code. But this doesn't seem to work.

if re.search(r'...$', 'abcde1234doc').group() in ['doc', 'rtf', 'txt'] == True:
    print'regex search matched!'
else:
    print'regex search not matched'

I expected the IF statement proceed with it's code when the regex search returns True, however the IF statement doesn't match and goes straight to the ELSE.

MrU
  • 129
  • 1
  • 8

1 Answers1

1

Boolean operators chain in Python.

x in y == z

means

x in y and y==z

You could write your condition as

if (re.search(r'...$', 'abcde1234doc').group() in ['doc', 'rtf', 'txt']) == True:

if you wanted, but you'd be better off just leaving off the ==True and sticking with

if re.search(r'...$', 'abcde1234doc').group() in ['doc', 'rtf', 'txt']:
khelwood
  • 55,782
  • 14
  • 81
  • 108