繁体   English   中英

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

[英]Replace every space after x chars with a “\n”

该函数的目标是将一个字符串拆分为多行以使其更具可读性。 目标是替换至少n个字符之后找到的第一个空格(因为字符串的开头,或者因为字符串中的最后一个\\ n)

惠普

  • 您可以假设字符串中没有\\n

Marcus plays soccer in the afternoon

f(10)应该导致

Marcus plays\nsoccer in\nthe afternoon

由于Marcus只有5个字符Marcus plays soccer in the afternoonMarcus plays soccer in the afternoon的第一个空间Marcus plays soccer in the afternoon 然后我们在plays后加一个\\n ,然后重新开始计数。 足球之后的空间因此被跳过,等等。

到目前为止尝试过

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

灵感来自

尝试更换

(.{10}.*?)\s

$1\n

在这里查看

例:

>>> 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