Notebook
  • Study hard and make progress every day
  • Mouka
    • Windows Internal
      • Helper Functions(todo:)
      • Find Kernel Module Address
      • Patch Guard Oops
      • Hook SSDT(Shadow)
      • Restore SSDT(Shadow)
      • Misc
        • Volatile in C
    • AntiCheat
      • Inject Defense
      • Injection Method
    • DriverDevelopment
      • 20180625
      • 20180626-27
    • Python
      • Python Tricks
        • 内置 http 服务器
        • 函数作为变量
        • "is" vs "=="
        • 直接变量值交换
        • 计算代码执行时间
        • 函数参数分解
        • 打印Python字典
        • 命名元组代替class
        • get()方法访问字典
        • 字典排序
        • 一次检查多个标志
        • 合并两个字典
        • re.sub使用替换函数
    • Algorithms
      • Greedy
        • 使括号平衡的最小交换次数
        • 埃及分数
      • DynamicProgramming
        • 0-1 背包问题
      • LeetCode
        • Count Primes
  • Honey
    • Python笔记
      • lxml库
      • os库
      • json文件读写
      • Scrapy
        • Scrapy安装与开始项目
        • Scrapy-Xpath
Powered by GitBook
On this page
  1. Mouka
  2. Python
  3. Python Tricks

re.sub使用替换函数

re.sub(pattern, repl, string, count=0, flags=0 )

Use function as repl

>>> text = 'UPPER PYTHON, lower python, Mixed Python'
>>> re.findall('python', text, flags=re.IGNORECASE)
['PYTHON', 'python', 'Python']
>>> re.sub('python', 'snake', text, flags=re.IGNORECASE)
'UPPER snake, lower snake, Mixed snake'

function will receive a match object as input parameter

def replace(m):
        word = 'snake'
        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

>>> re.sub('python', replace, text, flags=re.IGNORECASE)
'UPPER SNAKE, lower snake, Mixed Snake'
Previous合并两个字典NextAlgorithms

Last updated 6 years ago