Regular Expression In Conditional Statement Using Python 3
Solution 1:
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") isnotNone:
....
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
Solution 2:
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.
Post a Comment for "Regular Expression In Conditional Statement Using Python 3"