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