Why does re.sub in Python not work correctly on this test case?

后端 未结 4 1732
感动是毒
感动是毒 2021-01-21 06:47

Try this code.

test = \' az z bz z z stuff z  z \'
re.sub(r\'(\\W)(z)(\\W)\', r\'\\1_\\2\\3\', test)

This should replace all stand-alone z\'s w

4条回答
  •  孤城傲影
    2021-01-21 07:23

    If your goal is to make sure you only match z when it's a standalone word, use \b to match word boundaries without actually consuming the whitespace:

    >>> re.sub(r'\b(z)\b', r'_\1', test)
    ' az _z bz _z _z stuff _z  _z '
    

提交回复
热议问题