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