NoIdeaHowToFixThis NoIdeaHowToFixThis - 1 year ago 46
Python Question

Replace every space after x chars with a "\n"

The goals of the function is to split one single string into multiple lines to make it more readable. The goal is to replace the first space found after at least n characters (since the beginning of the string, or since the last "\n" dropped in the string)


  • you can assume no
    in the string


Marcus plays soccer in the afternoon

f(10) should result in

Marcus plays\nsoccer in\nthe afternoon

The first space in
Marcus plays soccer in the afternoon
is skipped because
is only 5 chars long. We put then a
and we start counting again. The space after soccer is therefore skipped, etc.

So far tried

def replace_space_w_newline_every_n_chars(n,s):
return re.sub("(?=.{"+str(n)+",})(\s)", "\\1\n", s, 0, re.DOTALL)

inspired by this

Answer Source

Try replacing




Check it out here.


>>> import re
>>> s = 'Marcus plays soccer in the afternoo
>>> re.sub(r'(.{9}.*?)\s', r'\1\n', s)
'Marcus plays\nsoccer in\nthe afternoon'