首页 > 解决方案 > 函数内部的函数如何在python中工作

问题描述

我是一个新的python学习者,从一些字符串练习开始。我想知道' matchcase '中的' replace '功能实际上是如何工作的。

import re
a = 'UPPER PYTHON, lower python, Mixed Python'

def matchcase(word):
    def replace(m):
        text = m.group()
        if text.isupper():
            return word.upper()
        elif text.islower():
            return word.lower()
        elif text[0].isupper():
            return word.capitalize()
        else:
            return word
    return replace

print (matchcase('conran'))

print (re.sub('python',matchcase('conran'),a , flags=re.IGNORECASE))

输出:UPPER CONRAN,下 conran,Mixed Conran

标签: pythonfunction

解决方案


re.sub 可以采用在每次匹配时调用的函数参数,而不是文本替换。

您的外部函数返回另一个可以访问传递的字符串的函数(高阶函数)(这称为闭包)。所以这个内部函数被 re.sub 用“python”调用并在相同的情况下返回“conran”。


推荐阅读