[Note: after posting on a regular schedule for most of the past year, I’ve decided to take a break and post things here on a less regular schedule for the time being.]

Last year, I wrote a post about using word wrapping as an interview question. Today, I want to briefly note that outside of an interview, this problem can be solved with the Python standard library, specifically the textwrap module. With textwrap, we can reproduce our earlier solution in only a few lines.

import re
import textwrap

s = """Our string...
to wrap"""

# Split the input into a list of paragraphs
paragraphs = re.split("\n\n+", s)

# Combine multiple spaces into one space
collapse_spaces = lambda paragraph: re.sub(r'\s+', r' ', paragraph.strip())

# Wrap one paragraph using the textwrap module
wrap_paragraph = lambda paragraph: textwrap.fill(collapse_spaces(paragraph),
  width=80, break_long_words=False)

print(s)
print("---")
print("\n\n".join(wrap_paragraph(p) for p in paragraphs))

Here are some outputs from that program for various values of s.

This is a very long, single line test string that I would like to see wrapped to 80 characters per line, in accordance with international law and general human decency.
---
This is a very long, single line test string that I would like to see wrapped to
80 characters per line, in accordance with international law and general human
decency.

This is a string
that is _less_ than 80 characters.

Crazy, right?

---
This is a string that is _less_ than 80 characters.

Crazy, right?
This string has...




    ...lots of newlines.

I've decided just to keep one newline between paragraphs, but this is definitely debatable and something that could be configured as an option in the future. Boy, how I drone on when I'm trying to make a long line.

---
This string has...

...lots of newlines.

I've decided just to keep one newline between paragraphs, but this is definitely
debatable and something that could be configured as an option in the future.
Boy, how I drone on when I'm trying to make a long line.
This   string    has    lots of extra    spaces.      It should end up            as           one        line.
---
This string has lots of extra spaces. It should end up as one line.
This is a string with oneExtremelyLongWord.AllWeCanDoHereIsPrintThisThingOnItsOwnLineAndWrapTheRestOfTheParagraphAroundIt.ThereIsNotAnyOtherGreatWayToHandle this that I can think of.
---
This is a string with
oneExtremelyLongWord.AllWeCanDoHereIsPrintThisThingOnItsOwnLineAndWrapTheRestOfTheParagraphAroundIt.ThereIsNotAnyOtherGreatWayToHandle
this that I can think of.