用“\ n”

时间:2016-06-16 11:49:39

标签: python regex

该函数的目标是将一个单独的字符串拆分为多行,以使其更具可读性。目标是替换在至少n个字符之后找到的第一个空格(从字符串的开头,或者从字符串中删除的最后一个“\ n”)

Hp

  • 您可以在字符串
  • 中假设没有\n

示例

Marcus plays soccer in the afternoon

f(10)应该导致

Marcus plays\nsoccer in\nthe afternoon

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

到目前为止尝试了

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

受到this

的启发

1 个答案:

答案 0 :(得分:2)

尝试替换

float

(.{10}.*?)\s

Check it out here

示例:

$1\n
相关问题