Home > Software engineering >  python: simplify return statement (trigraph?)
python: simplify return statement (trigraph?)

Time:11-26

Consider the following simple code:

import re

def my_match(s):
    if re.match("^[a-zA-Z] ", s):
         return True
    else:
         return False

Is there a way to collapse this in a single return statement? In C we could do for example:

return match("^[a-zA-Z] ", s) ? true : false;

Is there something similar in python?

CodePudding user response:

Python also supports this, although the syntaxes is a little different than most languages.

import re

def my_match(s):
    return True if re.match("^[a-zA-Z] ", s) else False

In general, the Python syntax is val_when_true if cond else val_when_false, compared to the cond ? val_when_true : val_when_false you see in other languages.

In your particular case though, you can just write:

import re

def my_match(s):
    return bool(re.match("^[a-zA-Z] ", s))

CodePudding user response:

Try this:

return True if match("^[a-zA-Z] ", s) else False

CodePudding user response:

re.match() returns a value that can be evaluated for truthiness. So if you don't need to return the exact values True and False, you can just directly return the result of the match() function:

def my_match(s):
    return re.match("^[a-zA-Z] ", s)

And then the caller can say:

if  my_match(x):
    ...
else:
    ...

Although in this specific case, my_match() becomes a mostly useless wrapper function, and you could just call re.match(...) directly.

if re.match(...):
   ...
else:
   ...

CodePudding user response:

The other answers show the trigraph equivalent in Python. But since Python also assigns truthiness to values and expressions, you could simply use:

my_match = lambda s : bool(re.match("^[a-zA-Z] ", s))
  • Related