python - More pythonic way to write this? -
i have code here:
import re def get_attr(str, attr): m = re.search(attr + r'=(\w+)', str) return none if not m else m.group(1) str = 'type=greeting hello=world' print get_attr(str, 'type') # greeting print get_attr(str, 'hello') # world print get_attr(str, 'attr') # none
which works, not particularly fond of line:
return none if not m else m.group(1)
in opinion cleaner if use ternary operator:
return (m ? m.group(1) : none)
but of course isn't there. suggest?
python has ternary operator. you're using it. it's in x if y else z
form.
that said, i'm prone writing these things out. fitting things on 1 line isn't great if sacrifice clarity.
def get_attr(str, attr): m = re.search(attr + r'=(\w+)', str) if m: return m.group(1) return none
Comments
Post a Comment