Issue 1702681: Prevent textwrap from breaking words at hyphens (original) (raw)

FWIW, one workaround is to "monkey patch" the module:

textwrap.TextWrapper.wordsep_re = re.compile(r'(\s+|(?<=[\w!"'&.,?])-{2,}(?=\w))')

Another workaround is to "hide" the hyphens during wrapping and then restore them.

def myfill(text, width=70, **kwargs): althyphen = chr(127) text = text.replace('-', althyphen) result = wrap(text, width, **kwargs) return result.replace(althyphen, '-')

That being said, I'm +1 on adding a keyword argument treating hyphens as non-breaking.