python中函数内部函数如何工作
我是一名新的python学习者,从一些字符串练习开始。我想知道“matchcase”中的“replace”函数实际上是如何工作的python中函数内部函数如何工作,python,function,Python,Function,我是一名新的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()
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、lower-CONRAN、Mixed-CONRANre.sub可以采用在每次匹配时调用的函数参数,而不是文本替换
外部函数返回另一个高阶函数,该函数可以访问传递的字符串,称为闭包。因此,这个内部函数由python的re.sub调用,并在相同的情况下返回conran。究竟什么是不清楚的?replace的工作原理与其他Python函数一样。您能否更具体地说明您不清楚的部分?return replace返回函数对象。这称为closure.return replace=>return replaceword,或者返回函数本身。在这种情况下,内部函数不是很有用。谢谢,现在我了解了内部函数的工作原理嘿,Pepijn,你能帮我把这个函数转换成一个类吗。我试过了,但没有马上成功。函数有什么问题吗?不要在不需要的时候使用类。