导航:首页 > 编程语言 > sub的用法python

sub的用法python

发布时间:2022-07-18 05:45:09

A. 小白求助大神python中findall()和sub()的结果

第一个问题,你搞错了,不是逗号,是两个空字符串,返回的结果列比里其实有三个元素。虽然看起来很像两个。所以,它找到了符合条件的三个对象,也就是['section{First', '', ''] 。右大括号的位置是理解的关键。

第二个问题。sub方法是用你指定的字符串替换‘匹配’上的字符串。前面我们匹配上了3个位置,将它们逐一替换,就得到了'subsection{}subsection{}}subsection{}'。注意其中那个蹦单的右大括号。

第三个问题。你使用了sub的分组引用功能。它在替换的同时会用匹配上的内容替换‘1’。你在前面匹配上了一个字符串和两个空格,将它们依次代入问题二结果中的三对大括号就能得到最终结果'subsection{section{First}subsection{}}subsection{}'

更多内容参考正则表达式和re模块

B. 如何用Python来进行查询和替换一个文本字符串

可以使用sub()方法来进行查询和替换,sub方法的格式为:sub(replacement, string[, count=0])

replacement是被替换成的文本

string是需要被替换的文本

count是一个可选参数,指最大被替换的数量

例子:

import re
p = re.compile(‘(blue|white|red)’)
print(p.sub(‘colour’,'blue socks and red shoes’))
print(p.sub(‘colour’,'blue socks and red shoes’, count=1))

输出:

colour socks and colour shoes
colour socks and red shoes

subn()方法执行的效果跟sub()一样,不过它会返回一个二维数组,包括替换后的新的字符串和总共替换的数量

例如:

import re
p = re.compile(‘(blue|white|red)’)
print(p.subn(‘colour’,'blue socks and red shoes’))
print(p.subn(‘colour’,'blue socks and red shoes’, count=1))

输出

(‘colour socks and colour shoes’, 2)

(‘colour socks and red shoes’, 1)

C. 帮忙解释一个python函数调用的问题

这个是sub的特殊用法,fn就是调用函数,它不用(), 等效于 fn(match对象)。

D. Python re.sub

【背景】
Python中的正则表达式方面的功能,很强大。
其中就包括re.sub,实现正则的替换。
功能很强大,所以导致用法稍微有点复杂。
所以当遇到稍微复杂的用法时候,就容易犯错。
所以此处,总结一下,在使用re.sub的时候,需要注意的一些事情。

解释具体的注意事项之前,先把其具体的解释贴出来:
re.sub

re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string 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 carriage return, 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. For example:
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
... r'static PyObject*\npy_\1(void)\n{',
... 'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example:
>>> def dashrepl(matchobj):
... if matchobj.group(0) == '-': return ' '
... else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
'Baked Beans & Spam'

The pattern may be a string or an RE object.
The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so sub('x*', '-', 'abc') returns '-a-b-c-'.
In addition to character escapes and backreferences as described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE.
Changed in version 2.7: Added the optional flags argument.

re.sub的功能
re是regular expression的所写,表示正则表达式
sub是substitute的所写,表示替换;
re.sub是个正则表达式方面的函数,用来实现通过正则表达式,实现比普通字符串的replace更加强大的替换功能;
举个最简单的例子:
如果输入字符串是:
?

1

inputStr = "hello 111 world 111"

那么你可以通过
?

1

replacedStr = inputStr.replace("111", "222")

去换成
"hello 222 world 222"
但是,如果输入字符串是:
?

1

inputStr = "hello 123 world 456"

而你是想把123和456,都换成222
(以及其他还有更多的复杂的情况的时候),
那么就没法直接通过字符串的replace达到这一目的了。
就需要借助于re.sub,通过正则表达式,来实现这种相对复杂的字符串的替换:
?

1

replacedStr = re.sub("\d+", "222", inputStr)

当然,实际情况中,会有比这个例子更加复杂的,其他各种特殊情况,就只能通过此re.sub去实现如此复杂的替换的功能了。
所以,re.sub的含义,作用,功能就是:
对于输入的一个字符串,利用正则表达式(的强大的字符串处理功能),去实现(相对复杂的)字符串替换处理,然后返回被替换后的字符串
其中re.sub还支持各种参数,比如count指定要替换的个数等等。
下面就是来详细解释其各个参数的含义。

re.sub的各个参数的详细解释
re.sub共有五个参数。
其中三个必选参数:pattern, repl, string
两个可选参数:count, flags

第一个参数:pattern
pattern,表示正则中的模式字符串,这个没太多要解释的。
需要知道的是:
反斜杠加数字(\N),则对应着匹配的组(matched group)
比如\6,表示匹配前面pattern中的第6个group
意味着,pattern中,前面肯定是存在对应的,第6个group,然后你后面也才能去引用
比如,想要处理:
hello crifan, nihao crifan
且此处的,前后的crifan,肯定是一样的。
而想要把整个这样的字符串,换成crifanli
则就可以这样的re.sub实现替换:
?

1
2
3

inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (\w+), nihao \1", "crifanli", inputStr);
print "replacedStr=",replacedStr; #crifanli

第二个参数:repl
repl,就是replacement,被替换,的字符串的意思。
repl可以是字符串,也可以是函数。

repl是字符串
如果repl是字符串的话,其中的任何反斜杠转义字符,都会被处理的。
即:
\n:会被处理为对应的换行符;
\r:会被处理为回车符;
其他不能识别的转移字符,则只是被识别为普通的字符:
比如\j,会被处理为j这个字母本身;
反斜杠加g以及中括号内一个名字,即:\g<name>,对应着命了名的组,named group
接着上面的举例:
想要把对应的:
hello crifan, nihao crifan
中的crifan提取出来,只剩:
crifan
就可以写成:
?

1
2
3

inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (\w+), nihao \1", "\g<1>", inputStr);
print "replacedStr=",replacedStr; #crifan

对应的带命名的组(named group)的版本是:
?

1
2
3

inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (?P<name>\w+), nihao (?P=name)", "\g<name>", inputStr);
print "replacedStr=",replacedStr; #crifan

repl是函数
举例说明:
比如输入内容是:
hello 123 world 456
想要把其中的数字部分,都加上111,变成:
hello 234 world 567
那么就可以写成:
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:

Version: 2013-05-02
Author: Crifan
Contact: admin (at) crifan.com
"""

import re;

def pythonReSubDemo():
"""
demo Pyton re.sub
"""
inputStr = "hello 123 world 456";

def _add111(matched):
intStr = matched.group("number"); #123
intValue = int(intStr);
addedValue = intValue + 111; #234
addedValueStr = str(addedValue);
return addedValueStr;

replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr);
print "replacedStr=",replacedStr; #hello 234 world 567

###############################################################################
if __name__=="__main__":
pythonReSubDemo();

第三个参数:string
string,即表示要被处理,要被替换的那个string字符串。
没什么特殊要说明。

第四个参数:count
举例说明:
继续之前的例子,假如对于匹配到的内容,只处理其中一部分。
比如对于:
hello 123 world 456 nihao 789
只是像要处理前面两个数字:123,456,分别给他们加111,而不处理789,
那么就可以写成:
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:

Version: 2013-05-02
Author: Crifan
Contact: admin (at) crifan.com
"""

import re;

def pythonReSubDemo():
"""
demo Pyton re.sub
"""
inputStr = "hello 123 world 456 nihao 789";

def _add111(matched):
intStr = matched.group("number"); #123
intValue = int(intStr);
addedValue = intValue + 111; #234
addedValueStr = str(addedValue);
return addedValueStr;

replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr, 2);
print "replacedStr=",replacedStr; #hello 234 world 567 nihao 789

###############################################################################
if __name__=="__main__":
pythonReSubDemo();

第五个参数:flags

关于re.sub的注意事项
然后再来整理一些,关于re.sub的注意事项,常见的问题及解决办法:

要注意,被替换的字符串,即参数repl,是普通的字符串,不是pattern
注意到,语法是:
?

1

re.sub(pattern, repl, string, count=0, flags=0)

即,对应的第二个参数是repl。
需要你指定对应的r前缀,才是pattern:
r"xxxx"

不要误把第四个参数flag的值,传递到第三个参数count中了
否则就会出现我这里:
【已解决】Python中,(1)re.compile后再sub可以工作,但re.sub不工作,或者是(2)re.search后replace工作,但直接re.sub以及re.compile后再re.sub都不工作
遇到的问题:
当传递第三个参数,原以为是flag的值是,
结果实际上是count的值
所以导致re.sub不功能,
所以要参数指定清楚了:
?

1

replacedStr = re.sub(replacePattern, orignialStr, replacedPartStr, flags=re.I); # can omit count parameter

或:
?

1

replacedStr = re.sub(replacePattern, orignialStr, replacedPartStr, 1, re.I); # must designate count parameter

才可以正常工作。

E. python 正则表达式re.sub函数替换内容的一个比较基础的问题

正则表达式一个比较常见的用途是找到所有模式匹配的字符串并用不同的字符串来替换它们。sub方法提供一个替换值,可以是字符串或函数,和一个要被处理的字符串。

1、这里的sub方法,是被编译成‘RegexObject’实例后的实例的方法

Sub(replacement,string[,count =0 ])

1)返回的字符串是在字符串中用RE最左边不重复的匹配来替换。如果模式没有被发现,字符将没有被改变的返回。
2)可选参数count是模式匹配后替换的最大次数;count必须是非负整数。缺省值是0表示替换所有的匹配。
例子:

2、模块级函数:sub方法

注:这些函数(包括sub函数)使用RE字符串作为第一个参数,而后面的参数与相应的“RegexObject”方法的参数相同,返回要么是None,要么是一个‘MatchObject’实例。
(实际sub返回的是字符串,,两者说法不一致,以实际为准)
Re.sub的作用在于:使用给定的替换内容将匹配模式的子字符串(最左端并且非重叠的子字符串)替换掉

3、作为替换的组号
在2的例子中,只是把一个字符串用其他的内容替换掉了。用replace这个字符串方法能轻松达到同样的效果。而正则表达式允许以更灵活的方式进行搜索,同时它们也允许进行功能更强大的替换。
见证re.sub强大功能的最简单方式就是在替换字符串中使用组号。在替换内容中以‘\\n’型式出现的任何转义序列都会被模式中与组n匹配的字符串替换掉。例如,假设要把‘*something*’用‘<em>someting</em>’替换掉,前者是在普通文本文档(比如Email)中进行强调的常用方法,而后者则是相应的HTML代码(用于网页)

这里把所有的* *含的字符串都替换掉了。刚开始我以为只替换*world*。记一笔。

F. Python字符串匹配的使用方法有哪些

1. re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

import re

line="this hdr-biz 123 model server 456"

pattern=r"123"

matchObj = re.match( pattern, line)

2. re.search 扫描整个字符串并返回第一个成功的匹配。

import re

line="this hdr-biz model server"

pattern=r"hdr-biz"

m = re.search(pattern, line)

3. Python 的re模块提供了re.sub用于替换字符串中的匹配项。

import re

line="this hdr-biz model args= server"

patt=r'args='

name = re.sub(patt, "", line)

4. compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。

import re

pattern = re.compile(r'\d+')

5. re.findall 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。

import re

line="this hdr-biz model args= server"

patt=r'server'

pattern = re.compile(patt)

result = pattern.findall(line)

6. re.finditer 和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。

import re

it = re.finditer(r"\d+","12a32bc43jf3")

for match in it:

print (match.group() )

关于Python字符串匹配的使用方法有哪些,环球青藤小编就和大家分享到这里了,学习是永无止境的,学习一项技能更是受益终身,所以,只要肯努力学,什么时候开始都不晚。如果您还想继续了解关于python编程的学习方法及素材等内容,可以点击本站其他文章学习。

G. python 中 re.sub 和 re.compile 是啥意思呀跪求大神解释。

在python中re是一个常用的模块,主要是通过正则表达式进行字符串处理。它的速度相对自己用 find, replace, split来说,通常更快。当然功能更强大。


正则表达式也是一种语言,所以如果通过re.compile把它编译成对象,会速度快很多。所以我们经常看到这样的语句

exp=re.compile("S+")
m=exp.search(bigtext)
printm.group(0)

这段话等同于

m=re.search("S+",bigtext)
printm.group(0)

re.sub则相当于字符串操作中的replace,比如

sometext=re.sub("(?isu)
","
",sometext)

上面这句话是将回车换行,变成换行。这是为了将windows下的文本文件移到linux下,防止某些软件不兼容所做的处理。


简单的说re.sub是做字符串替换的, re.compile是将正则表达式编译成一个对象,加快速度,并重复使用。

阅读全文

与sub的用法python相关的资料

热点内容
腰椎压缩性骨折吧 浏览:324
安卓怎么把软件改成火影忍者 浏览:702
手机如何切换软件商店服务器 浏览:325
江苏省python二级题型 浏览:231
文件编译器在哪 浏览:26
选择目录时此电脑的文件夹怎么删 浏览:25
狗狗币加密支付服务 浏览:897
怎么使用指南针APP确定方向 浏览:372
php读取图片并输出 浏览:321
如何组合多个pdf文件 浏览:669
工作表格excel取消加密 浏览:133
真空压缩袋手泵怎么用 浏览:426
镜面的命令 浏览:203
51单片机蓝牙模块有延迟 浏览:115
b解压药 浏览:569
跳空缺口指标源码怎么写 浏览:701
怎么杀掉服务器上所有进程 浏览:180
c语言中水仙花数的算法分析 浏览:495
心烦时玩儿的解压神器 浏览:497
linux安装的库文件 浏览:920