導航:首頁 > 編程語言 > 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相關的資料

熱點內容
個人雲和伺服器有什麼區別 瀏覽:202
愛戀 法國 百度雲 瀏覽:386
單片機rpc 瀏覽:297
arm能編譯的軟體 瀏覽:764
歐美電影激情合集 瀏覽:620
女主妓女 瀏覽:447
手指速演算法入門視頻 瀏覽:649
我的世界domcer伺服器怎麼私聊 瀏覽:890
vba文件夾查找 瀏覽:289
碼表單片機選擇 瀏覽:445
linux伺服器配置查詢 瀏覽:276
法國啄木鳥在線 瀏覽:489
這周周末不能去看電影的英文 瀏覽:460
哪裡在線看小電影 瀏覽:853
交換的一天女主角叫什麼名 瀏覽:973
為什麼安卓微信比蘋果微信版本低 瀏覽:139
vivo編譯速率 瀏覽:545
文件解壓不到指定位置 瀏覽:610
查看資料庫所在伺服器的ip地址 瀏覽:548
網友自拍網站 瀏覽:276