A C-like if statement

Paul Rubin http
Thu Feb 23 20:07:06 EST 2006


"Bob Greschke" <bob at passcal.nmt.edu> writes:
> I miss being able to do something like this in Python
> 
> 1f (I = a.find("3")) != -1:
>     print "It's here: ", I
> else:
>     print "No 3's here"
> 
> where I gets assigned the index returned by find() AND the if statement gets 
> to do its job in the same line.  Then you don't have to have another like 
> that specifically gets the index of the "3".  Is there a way to do this in 
> Python?

For regexps I sometimes do it with a specially created class instance.
Something like:
  
  save = Cache_match()

  if save.find(a, "3"):
    print "it's here:", save.result
  else:
    print "no 3's here"

Implementing Cache_match is left to you as an exercise.  It does make
your code a bit cleaner if you're doing lots of matching.



More information about the Python-list mailing list