How to properly iterate with re.sub() in Python

后端 未结 3 1566
北荒
北荒 2021-02-14 12:36

I want to make a Python script that creates footnotes. The idea is to find all strings of the sort \"Some body text.{^}{Some footnote text.}\" and replace them with

3条回答
  •  礼貌的吻别
    2021-02-14 13:14

    Any callable can be used, so you could use a class to track the numbering:

    class FootnoteNumbers(object):
        def __init__(self, start=1):
            self.count = start - 1
    
        def __call__(self, match):
            self.count += 1
            return "{}".format(self.count)
    
    
    new_body_text = re.sub(pattern, FootnoteNumbers(), text)
    

    Now the counter state is contained in the FootnoteNumbers() instance, and self.count will be set anew each time you start a re.sub() run.

提交回复
热议问题