0

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?

Mark
  • 6,052
  • 8
  • 61
  • 129
  • 2
    Does this answer your question? [Does Python have a ternary conditional operator?](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) – PM 77-1 Nov 25 '22 at 16:53
  • 1
    Trigraphs are something completely different. What you mean is a ternary operator. – Sören Nov 25 '22 at 17:23

4 Answers4

1

A more generell solution would be to use the following code line. It excludes a fit with length 0 as it specificly checks for the None statement. In this case an empty string is impossible but it is more explicit.

return re.match("^[a-zA-Z]+", s) is not None
NameVergessen
  • 598
  • 8
  • 26
Frank
  • 136
  • 1
  • 10
1

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))
CoffeeTableEspresso
  • 2,614
  • 1
  • 12
  • 30
0

The other answers show the ternary 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))
RufusVS
  • 4,008
  • 3
  • 29
  • 40
0

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:
   ...
John Gordon
  • 29,573
  • 7
  • 33
  • 58