# coding: utf-8
import re
# 注意P要从大写 要不然会出现错误:unexpected end of pattern
P = re.compile(r'(?P<word1>\w+) (?P<word2>\w+)')
s = 'i say, hello world!'
print P.sub(r'\g<word2> \g<word1>', s)
P = re.compile(r'(\w+) (\w+)')
print P.sub(r'\2 \1', s)
def func(m):
return m.group(1).title() + ' ' + m.group(2).title()
print P.sub(func, s)
'''
输出结果:
say i, world hello!
say i, world hello!
I Say, Hello World!
'''
记得括号里的P一定要大写!大写!大写!