python 正则表达式篇 - subn 用法

python 正则表达式篇 - subn 用法

代码

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @Software: PyCharm
# @virtualenv:workon
# @contact: contact information
# @Desc:subn
__author__ = '未昔/AngelFate'
__date__ = '2019/8/23 22:20'


def re_subn(con):
    """
    subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
    返回 (sub(repl, string[, count]), 替换次数)。
    :return:
    """
    import re

    p = re.compile(r'(\w+) (\w+)')

    print(p.subn(r'\2 \1', con))

    def func(m):
        return m.group(1).title() + ' ' + m.group(2).title()

    print(p.subn(func, con))


if __name__ == '__main__':
    con = 'i say, hello world!'
    print(re_subn(con))

结果

D:\import\python3.7\python.exe "E:/python/Study/小经验/python正则表达式篇 -  subn用法.py"
('say i, world hello!', 2)
('I Say, Hello World!', 2)
None

Process finished with exit code 0