Powerful perl paradigm I don't find in python

Nathan Hilterbrand nhilterbrand at gmail.com
Fri Jan 15 11:54:35 EST 2016



On 01/15/2016 04:24 AM, Charles T. Smith wrote:
> while ($str != $tail) {
>      $str ~= s/^(head-pattern)//;
>      use ($1);
> }

IDK...  maybe the OP is looking for something like this? :

import re

def do_something(matchobj):
     print("I found {}".format(matchobj.group(0)))
     return ""

tail = "END"
str = "FeeFieFooFumEND"
pattern = r"F.."

while(str and str != tail):
     oldstr = str
     str = re.sub(pattern, do_something, str, 1)
     if str == oldstr:
         break


Though I would probably change the perl code, too:

while ($str and $str != $tail) {
     $str ~= s/^(head-pattern)//;
     if ($1) {
        do_something($1);
     } else {
        last;
     }
}

Otherwise there is too much risk of an infinite loop if the string is 
(1) empty, or (2) never ends up being equal to "tail"

Nathan





More information about the Python-list mailing list