vendredi 17 juin 2016

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 playsnsoccer innthe afternoon

The first space in Marcus plays soccer in the afternoonis 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)", "\1n", s, 0, re.DOTALL)

inspired by this

Aucun commentaire:

Enregistrer un commentaire