Python爬虫开发-07--正则表达式-unexpected end of pattern-闹鬼!

# coding: utf-8
import re
# 注意P要从大写 要不然会出现错误:unexpected end of pattern
P = re.compile(r'(?P\w+) (?P\w+)') 
s = 'i say, hello world!'
print P.sub(r'\g \g', 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一定要大写!大写!大写!

你可能感兴趣的:(PythonPro)