1

I write my code that way, I want to assign matched values to 'm' but lst[1] may not including the pat I want. if it does, so I'll keep do something about 'm' eg: m.group(2).split() ....

  if re.match(pat, lst[1]):
       m=re.match(pat, lst[1])

But I don't want to repeat the re.match(pat, lst[1]) twice.

I want to achieve in that way

  if m = re.match(pat, lst[i])

but it shows me "invalid syntax error. any ideas?

4
  • In fact, I think you want to DRY (not repeat) yourself ;) Commented Aug 29, 2013 at 11:04
  • 5
    its like asking for using braces instead of indentation in Python Commented Aug 29, 2013 at 11:10
  • 1
    @ThePhysicist that's exactly what I thought when I read it. As it currently stands, OP is saying he doesn't want to not repeat himself, or equivalently that he does wish to repeat himself. Commented Aug 29, 2013 at 11:17
  • 1
    Why is this even a problem? If you just do m = re.match(pat, lst[i]) then m will be None if there are no matches; you can completely get rid of the if. Commented Aug 29, 2013 at 11:30

2 Answers 2

4

Just assign the value beforehand and check if it's None:

m = re.match(pat,lst[1])
if not m:
  del m
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you~ I forgot your solution
You're welcome! Coming from Ruby I'm sometimes tempted to use unless (a = ...) do syntax as well, which sadly (or luckily!?) does not work in Python...
ha I love Ruby , but not familiar enough
0

You can abuse for for your task.

def for_if(expression):
    if expression:
        yield expression

for m in for_if(re.match(pat, lst[1])):
    # work with m

or just

for m in (i for i in (re.match(pat, lst[1]),) if i):
    # do the same

This is not really helpful for readability, but is the only way to combine assignment and test.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.