[英]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 : 惠普
\\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 afternoon
在Marcus 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)
Try replacing 尝试更换
(.{10}.*?)\s
with 与
$1\n
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.