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
You want to avoid capturing the whitespace. Try using the 0-width word break \b, like this:
\b
re.sub(r'\bz\b', '_z', test)