2016-06-16 57 views
0

该函数的目标是将一个单独的字符串拆分为多行,以使其更具可读性。我们的目标是取代至少n个字符后找到的第一个空间(因为字符串的开头,或自上次“\ n”的字符串中丢弃)使用“ n”替换x个字符后的每个空格

的Hp

  • 你可以在串

Marcus plays soccer in the afternoon 
在假定没有

F(10)应导致

Marcus plays\nsoccer in\nthe afternoon 

Marcus plays soccer in the afternoon第一空间被跳过,因为Marcus只有5个字符长。我们在plays之后输入\n,然后我们再次开始计数。之后足球因此跳过空间等

到目前为止已经试过

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

通过this

+0

就谈不上什么问题,你必须在当前的代码,你的问题会更好。 – Maroun

+0

donno如何得到\ n后播放.. –

+0

拆分到单词,数。 –

回答

2

灵感试着用替换

(.{10}.*?)\s 

$1\n 

Check it out here

例子:

>>> import re 
>>> s = 'Marcus plays soccer in the afternoo 
>>> re.sub(r'(.{9}.*?)\s', r'\1\n', s) 
'Marcus plays\nsoccer in\nthe afternoon' 
相关问题