随笔 - 41, 文章 - 8, 评论 - 8, 引用 - 0
数据加载中……

[导入][python]关于re的sub中替换项是函数的笔记

今天逛百度知道,无意发现,原来re.sub中的替换项可以是一个函数。

这个函数接受一个参数。然后根据需求,返回应该替换的字符串。
IDLE 2.6.5     
>>> import re
>>> r=re.compile(r'a{1,2}')
>>> def myrepl(m):
 s=m.group(0)
 if s=='a':
  return 'one a'
 else:
  return 'two a'

 
>>> r.sub(myrepl,'a aa aaa')
'one a two a two aone a'
>>>

下面是摘自python文档(The Python Standard Library 8.2. re — Regular expression operations):

Ifrepl is a function, it is called for every non-overlapping occurrence ofpattern. The function takes a single match object argument, and returns the replacement string. For example:

>>> defdashrepl(matchobj):
... ifmatchobj.group(0)=='-':return' '
... else:return'-'
>>> re.sub('-{1,2}',dashrepl,'pro----gram-files')
'pro--gram files'

 

阅读全文
类别:Python 查看评论
文章来源:http://hi.baidu.com/mirguest/blog/item/42411d14ae7fcf0b972b43fc.html

posted on 2011-02-02 12:01 mirguest 阅读(2069) 评论(0)  编辑 收藏 引用 所属分类: python


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理