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
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:
z
\b
>>> re.sub(r'\b(z)\b', r'_\1', test) ' az _z bz _z _z stuff _z _z '