help converting some perl code to python

Peter Otten __peter__ at
Fri Nov 4 12:47:49 CET 2005

eight02645999 at wrote:

> i need help with converting a piece of perl code to python

> the problem is the '..' operator in perl. Is there any equivalent in
> python?

Here is a class that emulates the .. operator:

import sys
import re

start, files, end = map(re.escape, ["[start]", "[files]", "[end]"])

class Section(object):
    def __init__(self, start, end):
        self.start = re.compile(start).match
        self.end = re.compile(end).match
        self.inside = False
    def __contains__(self, line):
        result = self.inside
        if result:
            if self.end(line):
                self.inside = False
            if self.start(line):
                result = self.inside = True
        return result

first = Section(start, files)
second = Section(files, end)
for line in sys.stdin:
    line = line[:-1]
    if line in first:
        # your code
    if line in second:
        # your code

However, the simpler

import sys

start, files, end = "[start]", "[files]", "[end]"
keys = set([start, files, end])

key = None
for line in sys.stdin:
    line = line[:-1]
    if line in keys:
        key = line
    elif key == start:
        # your code
    elif key == files:
        # your code

might work even better because 'your code' doesn't get to see the sections'
begin/end markers.


More information about the Python-list mailing list