Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!
like image 887
Holy Mackerel Avatar asked May 01 '13 14:05

Holy Mackerel


People also ask

How do you break a long string into multiple lines in Python?

You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.

How do you split text into lines in Python?

Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break(optional). Parameters: keepends (optional): When set to True line breaks are included in the resulting list.

How do you split a long text in Python?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.

How do you split a string with fixed length in Python?

To split a string into fixed size chunks:Import the wrap() method from the textwrap module. Pass the string and the max width of each slice to the method. The wrap() method will split the string into a list with items of max length N.


1 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!
>>>
like image 98
piokuc Avatar answered Sep 22 '22 23:09

piokuc