1

I am self-studying Python 3 on Sololearn course. And I am now learning regular expression.

Here is the source code:

import re

pattern = r"spam"

if re.match(pattern, "spamspamspam"):
    print("Match")
else:
    print("No match")

--- according to Sololearn Python 3 Tutorial Course ---

The condition in if statement is quite confusing me. To my knowlegde I have gained, the condition in if statement should be in boolean expression. However, the re.match function, determines whether it matches the beginning of a string, does not return boolean value (If it matches, the function returns an object representing the match. If not, it returns None).

Therefore, I do not quite understand the if statement of the above code? Can anyone give me some explanations?

Le Quynh Anh
  • 111
  • 1
  • 12
  • 1
    You can see the truth evaluation here, https://docs.python.org/2/library/stdtypes.html#truth-value-testing – Dalvenjia Jul 11 '17 at 17:57

2 Answers2

4

Observe the output of re.match:

In [2473]: pattern = r"spam"

In [2474]: re.match(pattern, "spamspamspam")
Out[2474]: <_sre.SRE_Match object; span=(0, 4), match='spam'>

This returns a match object. Now, if we change our pattern a bit...

In [2475]: pattern = r"ham"

In [2477]: print(re.match(pattern, "spamspamspam"))
None

Basically, the truth value of None is False, while that of the object is True. The if condition evaluates the "truthiness" of the result and will execute the if body accordingly.

Your if condition can be rewritten a bit, like this:

if re.match(pattern, "spamspamspam") is not None:
    ....

This, and if re.match(pattern, "spamspamspam") are one and the same.

You should know about how the "truthiness" of objects are evaluated, if you are learning python. All nonempty data structures are evaluated to True. All empty data structures are False. Objects are True and None is False.

In [2482]: if {}:
      ...:     print('foo')
      ...: else:
      ...:     print('bar')
      ...:     
bar

In [2483]: if ['a']:
      ...:     print('foo')
      ...: else:
      ...:     print('bar')
      ...:     
foo
cs95
  • 379,657
  • 97
  • 704
  • 746
0

Python uses 'Truthy' and 'Falsy' values. Therefore, any match would be truthy and a None would be falsy. This concept extends to many places in the language, like checking if there is anything in a list:

if []:
    print("True")
else:
    print("False")

Will print false.

Check out this question for more information.

bendl
  • 1,583
  • 1
  • 18
  • 41