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!

Answers


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!
>>>

Need Your Help

How to force an app language that is not listed in Android settings?

android android-resources

I have a free open source app that already supports multiple languages. To test the languages I switch the phone's setting | language and everything works just fine.

How can I catch UTM Cookies values?

c# cookies google-analytics httpwebrequest webrequest

I'm trying to Log into a website using WebRequests in C# But the website is using Google-Analytics libraries which is making some UTM-Cookies