Python_API_String Services_re.sub

API文档: re.sub(pattern,repl,string[, count, flags])

Return the string obtained by replacing the leftmost non-overlapping occurrences ofpattern instring by the replacement repl. If the pattern isn’t found,string is returned unchanged.repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is,\n is converted to a single newline character,\r is converted to a linefeed, and so forth. Unknown escapes such as\j are left alone. Backreferences, such as\6, are replaced with the substring matched by group 6 in the pattern.


翻译文档:

        参数:

              pattern:匹配字符串的规则

              repl:可以替换的字符串也可以是处理的函数

              string:目标字符串

              [count]:匹配替换的次数

              [flags]:一些小标记,匹配时忽略字符串的大小写

        描述:

              返回string的字符串副本,根据匹配模式进行字符串替换和处理操作。

例子:

#! /usr/bin/env python
#coding=utf-8

import re

#匹配后处理函数
def dashrepl(matchObj):
    if matchObj.group(0)=='-':
        return ' '
    else:
        return '-'

print u'API文档例子:'+re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
    r'static PyObject*\npy_\1(void)\n{',
    'def myfunc():')

#匹配字符串,替换字符串
print u'repl替换字符串:'+re.sub('-{1,1}','+','pro----gram-files')

#匹配字符串,调用dashrepl处理替换字符串
print u'repl为函数处理替换的字符串:'+re.sub('-{1,2}',dashrepl,'pro----gram-files')


#匹配替换匹配的次数
print u'替换匹配的次数:'+re.sub('-{1,1}','+','pro----gram-files',2)

#忽略匹配字符串的大小写
print u'flags 忽略字符串大小写:'+re.sub(r'\sAND\s',' & ','Baked Beans And Spam',flags=re.IGNORECASE)

输出:

API文档例子:static PyObject*
py_myfunc(void)
{
repl替换字符串:pro++++gram+files
repl为函数处理替换的字符串:pro--gram files
替换匹配的次数:pro++--gram-files
flags 忽略字符串大小写:Baked Beans & Spam






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值