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?

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

I know comments aren't here for this, but this a really good, well-written and complete answer (+1), congrats on 10k! =)
@ViníciusAguiar Thanks! Appreciate ya.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.