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

后端 未结 4 1739
感动是毒
感动是毒 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:37

    You want to avoid capturing the whitespace. Try using the 0-width word break \b, like this:

    re.sub(r'\bz\b', '_z', test)
    

提交回复
热议问题