Formatting a string by word at a specific character length
Question: I don't see this question anywhere in the database - if it's a duplicate,
please let me know!

I'm trying to format a string to a certain length by word; I have a string of
arbitrary length and I would simply like to add newlines in every **n**
characters, separated by word so that the string is not split in the middle of
a word.

    
    
    str = "This is a string with length of some arbitrary number greater than 20"
    count=0
    tmp=""
    for word in str.split():
       tmp += word + " "
       count += len(word + " ")
       if count > 20:
          tmp += "\n"
          count = 0
    str = tmp
    print str
    

I'm certain that there is an embarrassingly simple Pythonic way to do this,
but I don't know what it is.

Suggestions?


Answer: Use the [textwrap](http://docs.python.org/library/textwrap.html) module. For
your case
[textwrap.fill](https://docs.python.org/2/library/textwrap.html#textwrap.fill)
should have it:

    
    
    >>> import textwrap
    >>> s = "This is a string with length of some arbitrary number greater than 20"
    >>> print textwrap.fill(s, 20)
    This is a string
    with length of some
    arbitrary number
    greater than 20
    

