简体   繁体   中英

How do regex objects work in Python loops?

I am constructing an if statement on Python that prints something when regex's match function founds a coincidence. I would like to know why the if statement works when my statement's condition is not a boolean (I think so).

import re

coincidence = re.match(r'\w{3}', 'abc')

if coincidence:
  print('There\'s a match')

which yields:

"There's a match"

Why does it work?

Python types have a "truthiness" value associated. You can try it out by executing bool() on different objects. The most obvious example would be integers:

bool(1)

> True

bool(0)

> False

but it goes beyond. bool("") will be False , while any other non-empty string will be True . Empty lists, dicts, tuples are False , but turn to True as soon as they are not empty. This is determined by the __bool__ class method, which dictates what should be evaluated whenever bool() is called on the object.

In the case of the output of the re.match function, it will either return None if it doesn't find the pattern (which evaluates to False ), or a re.Match object (which evaluates to True ).

That's why in your case, since the pattern is found sucessfully, the condition of the if clause evaluates to True.

When a match is found using re.match() a re.match() object is returned. In your case this is;

<re.Match object; span=(0, 3), match='abc'>

This means that the variable coincidence has a value that when cast by bool() returns True

bool(coincidence)
True

If a match is not found, None is returned, which always equates to False ;

coincidence = re.match(r'\w{5}', 'abc')
print(coincidence)
#None
bool(coincidence)
#False

Your statement boils down to is coincidence True , which when returning an object it is equal to True .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM