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!
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.
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.
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.
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.
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!
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With