NoIdeaHowToFixThis NoIdeaHowToFixThis - 5 months ago 10
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)

Hp:


  • you can assume no
    \n
    in the string



Example

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
Marcus
is only 5 chars long. We put then a
\n
after
plays
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

Try replacing

(.{10}.*?)\s

with

$1\n

Check it out here.

Example:

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