简体   繁体   中英

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM