Skip to content Skip to sidebar Skip to footer

Split A String Into Pieces Of Max Length X - Split Only At Spaces

I have a long string which I would like to break into pieces, of max X characters. BUT, only at a space (if some word in the string is longer than X chars, just put it into its own

Solution 1:

Use the textwrap module (it will also break on hyphens):

importtextwraplines= textwrap.wrap(text, width, break_long_words=False)

If you want to code it yourself, this is how I would approach it: First, split the text into words. Start with the first word in a line and iterate the remaining words. If the next word fits on the current line, add it, otherwise finish the current line and use the word as the first word for the next line. Repeat until all the words are used up.

Here's some code:

text = "hello, this is some text to break up, with some reeeeeeeeeaaaaaaally long words."
n = 16

words = iter(text.split())
lines, current = [], next(words)
for word in words:
    iflen(current) + 1 + len(word) > n:
        lines.append(current)
        current = word
    else:
        current += " " + word
lines.append(current)

Post a Comment for "Split A String Into Pieces Of Max Length X - Split Only At Spaces"