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