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

后端 未结 3 1558
北荒
北荒 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 12:58

    It seems like a good fit for a closure:

    def make_footnote_counter(start=1):
        count = [start - 1] # emulate nonlocal keyword
        def footnote_counter(match):
            count[0] += 1
            return "%d" % count[0]
        return footnote_counter
    
    new_body_text = re.sub(pattern, make_footnote_counter(), text)
    

提交回复
热议问题