简体   繁体   English

将x字符后的每个空格替换为“ \\ n”

[英]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) 目标是替换至少n个字符之后找到的第一个空格(因为字符串的开头,或者因为字符串中的最后一个\\ n)

Hp : 惠普

  • you can assume no \\n in the string 您可以假设字符串中没有\\n

Example

Marcus plays soccer in the afternoon

f(10) should result in f(10)应该导致

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. 由于Marcus只有5个字符Marcus plays soccer in the afternoonMarcus plays soccer in the afternoon的第一个空间Marcus plays soccer in the afternoon We put then a \\n after plays and we start counting again. 然后我们在plays后加一个\\n ,然后重新开始计数。 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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