Python if output of a function

Asked by At

I am using the following code to find repeated characters in a string

import re

m ='([A-Za-z0-9])\1+',S.strip())

if m:

I am not sure why "if m:" works for me and what does it do? Does it check if m exists? (which I believe it should exist anyway), does it check if the value of m is bigger than zero?

P.S: If my input string (S) has no repeated value, then print(m) gives me an error.

1 Answers

ForceBru On Best Solutions

if m: evaluates the expression m and checks if its value is "truthy", that is, if bool(m) is True. If it is, the body of the if block is executed.

If the name m doesn't exist, a NameError will be produced while evaluating the expression m.

Also, if S doesn't have a repeated value (for example, it's empty), print(m) will not give you an error:

>>> S = ''  # empty
>>> import re
>>> m ='([A-Za-z0-9])\1+',S.strip())
>>> print(m)
None  # not an error: this just indicates that the regex didn't find anything

Note that bool(None) == False.