2

Why does

not re.match("c", "cat")

return False, but

re.match("c", "cat")

Does not return True but instead returns the location of the object in memory. I can't find a way to make this statement return true, but I know it is true because:

if re.match("c", "cat"):
    print "Yes!"

returns "Yes!".

As I said, this is of no practical significance, at least not at the moment, but it does puzzle me.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
user3426752
  • 415
  • 1
  • 8
  • 17
  • 2
    *I can't find a way to make this statement return true* -- just explicitly convert it to `bool`: `bool(re.match("c", "cat"))`. – GingerPlusPlus Mar 20 '16 at 20:34
  • 3
    See https://docs.python.org/2/library/stdtypes.html#truth-value-testing - everything in Python can be evaluated in a Boolean context (using `if`, `not`, etc.). The match will return a result (truthy) or `None` (falsy). – jonrsharpe Mar 20 '16 at 20:36

3 Answers3

6

Use bool() to convert to a boolean value (true / false):

bool(re.match("c", "cat")) == true

When you use re.match("c", "cat") in your if statement, it is automatically converted to a boolean value, true, that is why it will return Yes!

Using not will automatically convert it to a boolean value, then invert it, therefore:

not re.match("c", "cat") == false
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
4

The function re.match() returns a match object if there is a match, or None if there's not.

To create a bool from that you can use:

if re.match(...) is not None:

However, in Python that's not strictly necessary: take a look at e.g. this thread for more on Python's "truthy" and "falsy" values.

Community
  • 1
  • 1
Jens
  • 8,423
  • 9
  • 58
  • 78
1

Well, focus on this:

not re.match("c", "cat")

Here re.match("c", "cat") will return the "location of the object in memory", as you said. That's something not False.

So now, not re.match("c", "cat") will result in:

not not False

which results to:

False

Of course, this kind of thinking can be applied to logical conditions too, like a condition of an if statement.

gsamaras
  • 71,951
  • 46
  • 188
  • 305