Holy Mackerel
Holy Mackerel

Reputation: 3279

Break up long line of text into lines of fixed width in Python 2.7

How would I break up a long string, at the spaces where possible, inserting hyphens if not, with an indent for all lines apart from the first line?

so, for a working function, breakup():

splitme = "Hello this is a long string and it may contain an extremelylongwordlikethis bye!"
breakup(bigline=splitme, width=20, indent=4)

would output:

Hello this is a long
    string and it
    may contain an
    extremelylongwo-
    rdlikethis bye!

Upvotes: 6

Views: 3842

Answers (1)

piokuc
piokuc

Reputation: 26184

There is a standard Python module for doing this: textwrap:

>>> import textwrap
>>> splitme = "Hello this is a long string and it may contain an extremelylongwordlikethis bye!"
>>> textwrap.wrap(splitme, width=10)
['Hello this', 'is a long', 'string and', 'it may', 'contain an', 'extremelyl', 'ongwordlik', 'ethis bye!']
>>> 

It doesn't insert hyphens when breaking words, though. The module has a shortcut function fill which concatenates the list produced by wrap so it's just one string.

>>> print textwrap.fill(splitme, width=10)
Hello this
is a long
string and
it may
contain an
extremelyl
ongwordlik
ethis bye!

To control indentation, use keyword arguments initial_indent and subsequent_indent:

>>> print textwrap.fill(splitme, width=10, subsequent_indent=' ' * 4)
Hello this
    is a
    long
    string
    and it
    may co
    ntain
    an ext
    remely
    longwo
    rdlike
    this
    bye!
>>>

Upvotes: 12

Related Questions