Question:
I am trying to create a program that finds people with first and last names using regular expressions. Does anyone know the difference between the Boolean in code 1 and code 2? Repl link: https://replit.com/@jonathanessombe/new-attempt#test.py
import re
names = ['Finn Bindeballe',
'Geir Anders Berge',
'HappyCodingRobot',
'Ron Cromberge',
'Sohil']
# Find people with first and last name only
# code 1
for name in names:
reg = '^\w+\s+\w+'
result = re.search(reg, name)
if result == True:
print(name)
# code 2
for name in names:
reg = '^\w+\s+\w+'
result = re.search(reg, name)
if result:
print(name)
The function re.search returns a re.Match object. This object is never directly equal to True so the condition in code 1 always fails.
In code 2, the condition
if result:
is basically equivalent to:
if bool(result):
because python will convert the condition to a bool if it was not already one.
Most objects in python are “truthy”, meaning bool(o) is True. There are a few falsy objects, these include None (which re.search returns if the string does not match), False, number objects equal to 0, and empty collections.
Therefore, code 2 condition only fails if re.search does not match (returning None).