Split a row without breaking a row into a list of rows with the maximum number of columns

I have a long line (several paragraphs) that I need to split into a list of line lines. The definition of what the string does is based on:

  • The number of characters in a row is less than or equal to X (where X is a fixed number of columns per row _)
  • OR, there is a new line in the original line (which will force a new "line" to be created.

I know I can do it algorithmically, but I was wondering if python has something that can handle this thing. This is essentially a word wrapping line.

And by the way, the output lines should be split at the boundaries of words, and not at the boundaries of characters.

Here is an example of input and output:

Input:

"Within eight hours of Wilson outburst, his Democratic opponent, former-Marine Rob Miller, had received nearly 3,000 individual contributions raising approximately $100,000, the Democratic Congressional Campaign Committee said. Wilson, a conservative Republican who promotes a strong national defense and reining in the size of government, won a special election to the House in 2001, succeeding the late Rep. Floyd Spence, RS.C. Wilson had worked on Spence staff on Capitol Hill and also had served as an intern for Sen. Strom Thurmond, RS.C." 

Output:

 "Within eight hours of Wilson outburst, his" "Democratic opponent, former-Marine Rob Miller," " had received nearly 3,000 individual " "contributions raising approximately $100,000," " the Democratic Congressional Campaign Committee" " said." "" "Wilson, a conservative Republican who promotes a " "strong national defense and reining in the size " "of government, won a special election to the House" " in 2001, succeeding the late Rep. Floyd Spence, " "RS.C. Wilson had worked on Spence staff on " "Capitol Hill and also had served as an intern" " for Sen. Strom Thurmond, RS.C." 
+6
python text-manipulation
source share
2 answers

EDIT

What you are looking for is textwrap , but only part of the solution is not complete. To accept a new line, you must do this:

 from textwrap import wrap '\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitlines()]) >>> print '\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitlines()]) Within eight hours of Wilson outburst, his Democratic opponent, former-Marine Rob Miller, had received nearly 3,000 individual contributions raising approximately $100,000, the Democratic Congressional Campaign Committee said. Wilson, a conservative Republican who promotes a strong national defense and reining in the size of government, won a special election to the House in 2001, succeeding the late Rep. Floyd Spence, RS.C. Wilson had worked on Spence staff on Capitol Hill and also had served as an intern for Sen. Strom Thurmond 
+13
source share

You probably want to use the textwrap function in the standard library:

http://docs.python.org/library/textwrap.html

+4
source share

All Articles