Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string into pieces of max length X - split only at spaces

Tags:

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 piece).

I don't even know how to begin to do this ... Pythonically

pseudo code:

declare a list
while still some string left:
   take the fist X chars of the string
   find the last space in that
   write everything before the space to a new list entry
   delete everything to the left of the space

Before I code that up, is there some python module that can help me (I don't think that pprint can)?

like image 285
Mawg says reinstate Monica Avatar asked Aug 20 '15 15:08

Mawg says reinstate Monica


People also ask

How do you split a string in space?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you split a string at every space in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How split a string by space in C#?

String. Split can use multiple separator characters. The following example uses spaces, commas, periods, colons, and tabs as separating characters, which are passed to Split in an array . The loop at the bottom of the code displays each of the words in the returned array.


1 Answers

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

import textwrap
lines = 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:
    if len(current) + 1 + len(word) > n:
        lines.append(current)
        current = word
    else:
        current += " " + word
lines.append(current)
like image 135
tobias_k Avatar answered Nov 14 '22 22:11

tobias_k