Locane Locane - 3 months ago 10
Python Question

Formatting a string by word at a specific character length

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 module. For your case 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
Comments