开发者

re.sub(...) replacing leftmost occurrences?

开发者 https://www.devze.com 2023-03-18 23:20 出处:网络
$ pydoc re.sub : sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost

$ pydoc re.sub :

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.

>>> re.sub('ROAD', 'RD.', 'BRRROADBBRROAD ROAD ROAD MY ROAD')
'BRRRD.BBRRD. RD. RD. MY RD.'

I don't quite understand the meaning of leftmost 开发者_StackOverflow社区in the python documentation. As far as I can see, it seems re.sub(...) is replacing all occurrences of pattern with repl


Note the 's' ending leftmost non-overlapping occurrences.

re.sub replaces all occurrences. You can use the optional count argument to limit the amount of replacements it does.

"Leftmost non-overlapping" means that if several occurrences are overlapping and can be potentially replaced, only the leftmost will:

>>> str = 'AABBBBAA'
>>> re.sub('BBB', 'CCC', str)
'AACCCBAA'

As you can see, there two (overlapping) occurrences of BBB here. Only the leftmost is replaced.


You can see what leftmost means in this example

>>> import re
>>> re.sub('haha', 'Z', 'hahaha')
'Zha'

Note we did not see 'haZ' which would have been rightmost substitution.

0

精彩评论

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