擅长:python、mysql、java
<p>你可以,我认为你必须这样做,因为它确实是一个优化函数,使用</p>
<pre><code>re.sub(pattern, repl, string[, count, flags])
</code></pre>
<p>findall_replace()</strong>函数之所以很长,是因为在每次匹配时,都会创建一个新的字符串对象,您将通过执行以下代码看到:</p>
<pre><code>ch = '''qskfg qmohb561687ipuygvnjoihi2576871987uuiazpoieiohoihnoipoioh
opuihbavarfgvipauhbi277auhpuitchpanbiuhbvtaoi541987ujptoihbepoihvpoezi
abtvar473727tta aat tvatbvatzeouithvbop772iezubiuvpzhbepuv454524522ueh'''
import re
def findall_replace(text, reg, rep):
for match in reg.findall(text):
text = text.replace(match, rep)
print id(text)
return text
pat = re.compile('\d+')
rep = 'AAAAAAA'
print id(ch)
print
print findall_replace(ch, pat, rep)
</code></pre>
<p>注意,在这段代码中,我将<code>output = text.replace(match, rep)</code>替换为<code>text = text.replace(match, rep)</code>,否则只替换最后一个出现的。</p>
<p>finditer_replace()的长度与findall_replace()的长度相同:重复创建字符串对象。但是前者使用迭代器re.finditer(),而后者则在list对象之前构造,因此它更长。这就是迭代器和非迭代器的区别。</p>