python - 函数内部的函数如何在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
解决方案
re.sub 可以采用在每次匹配时调用的函数参数,而不是文本替换。
您的外部函数返回另一个可以访问传递的字符串的函数(高阶函数)(这称为闭包)。所以这个内部函数被 re.sub 用“python”调用并在相同的情况下返回“conran”。
推荐阅读
- github - 使用 API 获取 GitHub 私有仓库的拉取请求评论评论
- android - 为什么尝试使用 Unity 拍照时相机视图太宽且不清晰?
- chatbot - 无法在 Botium 报告中展开对话
- javascript - 如何在图片悬停时在 CSS 中创建分离动画?
- python-3.x - 如何将对象反序列化为与python有关系的表
- java - 清单中存在的项目模型 (json) 中缺少标识符
- node.js - Postgres + NodeJS 插入,但不结束脚本
- docker - docker-compose 在多个服务之间共享本地绑定卷
- android - 如何将 dataBinding 与 spinner 一起使用并获取当前值?
- python - 将多个散景 html 文件添加到 django 模板