I am using the following code to find repeated characters in a string
import re
S=input()
m = re.search(r'([A-Za-z0-9])\1+',S.strip())
if m:
print(m.group(1))
else:
print(-1)
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.
if m:
evaluates the expressionm
and checks if its value is "truthy", that is, ifbool(m)
isTrue
. If it is, the body of theif
block is executed.If the name
m
doesn't exist, aNameError
will be produced while evaluating the expressionm
.Also, if
S
doesn't have a repeated value (for example, it's empty),print(m)
will not give you an error:Note that
bool(None) == False
.