[英]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 afternoon
在Marcus 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.