[issue1859] textwrap doesn't linebreak on "\n"

Otto Kekäläinen report at bugs.python.org
Thu Apr 12 08:47:39 CEST 2012

Otto Kekäläinen <otto at seravo.fi> added the comment:

As a note to comments msg60038-msg60040, for anybody like me who ended up here after Googling around on how to do wordwrap in Python:

The function textwrap in Python is for single strings/paragraphs only, and it does not work as wordwrap normally works in text editors or other programming languages (eg. Wordwrap in Python).

If you want to do wordwrap or a block of text, run something like this:

new_msg = ""
lines = msg.split("\n")

for line in lines:
    if len(line) > 75:
        w = textwrap.TextWrapper(width=75, break_long_words=False)
        line = '\n'.join(w.wrap(line))

    new_msg += line + "\n"

An use case example for this would be, if you have a email message and you want to apply word wrapping to it, so that no line would be over 78 characters.

nosy: +otto

Python tracker <report at bugs.python.org>

More information about the Python-bugs-list mailing list