Issue
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?
Solution
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))
Answered By - CoffeeTableEspresso
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.