开发者

In Python, how do I do a string replacement AND retrive the replaced substring?

开发者 https://www.devze.com 2022-12-24 01:47 出处:网络
In Perl, I would write: $x = \"abbbc\"; $x开发者_如何转开发 =~ s/(b+)/z/; print \"Replaced $1 and ended up with $x\\n\";

In Perl, I would write:

$x = "abbbc";
$x开发者_如何转开发 =~ s/(b+)/z/;
print "Replaced $1 and ended up with $x\n";
# "Replaced bbb and ended up with azc"

How do I do this in Python -- do a regular-expression string replacement and record what it was that got replaced?


Python does not simultaneously return a match and a substitution. Calling group(0) on a returned Match object will find the matched substring:

>>> r=re.compile('(b+)')
>>> r.search('abbbc')
<_sre.SRE_Match object at 0x7f04af497af8>
>>> r.search('abbbc').group(0)
'bbb'
>>> r.sub('z', 'abbbc')
'azc'
0

精彩评论

暂无评论...
验证码 换一张
取 消