The shortest way to split a long line (add space) after 60 characters?

I process a bunch of lines and display them on a web page.

Unfortunately, if a line contains a word longer than 60 characters, it makes my design explode.

So I'm looking for the easiest and most efficient way to add a space after every 60 characters without spaces in the string in python.

I just came up with awkward solutions, for example, using str.find(" ") twice and check if the index difference is > 60 different.

Any ideas appreciated, thanks.

+4
source share
3 answers
  >>> import textwrap
 >>> help (textwrap.wrap)
 wrap (text, width = 70, ** kwargs)
     Wrap a single paragraph of text, returning a list of wrapped lines.

     Reformat the single paragraph in 'text' so it fits in lines of no
     more than 'width' columns, and return a list of wrapped lines.  By
     default, tabs in 'text' are expanded with string.expandtabs (), and
     all other whitespace characters (including newline) are converted to
     space.  See TextWrapper class for available keyword args to customize
     wrapping behavior.
 >>> s = "a" * 20
 >>> s = "\ n" .join (textwrap.wrap (s, width = 10))
 >>> print s
 aaaaaaaaaaa
 aaaaaaaaaaa

Any additional inserted lines will be treated as space when the web page is processed by the browser.

As an alternative:

 def break_long_words(s, width, fix): return " ".join(x if len(x) < width else fix(x) for x in s.split()) def handle_long_word(s): # choose a name that describes what action you want # do something return s s = "a" * 20 s = break_long_words(s, 60, handle_long_word) 
+5
source
 def make_wrappable(your_string): new_parts = [] for x in your_string.split(): if len(x)>60: # do whatever you like to shorten it, # then append it to new_parts else: new_parts.append(x) return ' '.join(new_parts) 
0
source
 def splitLongWord ( word ): segments = list() while len( word ) > 0: segments.append( a[:60] ) word = a[60:] return ' '.join( segments ) myString = '...' # a long string with words that are longer than 60 characters words = list() for word in myString.split( ' ' ): if len( word ) <= 60: words.append( word ) else: words.extend( splitLongWord( word ) ) myString = ' '.join( words ) 
0
source

All Articles