今川館

都内勤務の地味OLです

re.subにはcallableなオブジェクトを渡せる

python-mini-hackathonで教えてもらった。
知らなかった。

以下、例を殴り書き。

import re


def main():
    text = """ 
        name = %NAME%
        age = %AGE%
        location = %LOCATION%
    """
    pattern = r"%([A-Z]+)%"
    values = { 
        "NAME" : "easy",
        "AGE" : "13",
    }   
    def fn(match_obj):
        key = match_obj.group(1)
        return values.get(key, "") 

    print re.sub(pattern, fn, text)


if __name__ == "__main__":
    main()

実行結果

        name = easy
        age = 13
        location =