Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
每n个字符插入一个换行符,使用Python在换行符上重置n_Python_Regex_String_Count_Line Breaks - Fatal编程技术网

每n个字符插入一个换行符,使用Python在换行符上重置n

每n个字符插入一个换行符,使用Python在换行符上重置n,python,regex,string,count,line-breaks,Python,Regex,String,Count,Line Breaks,我从Jira REST Api中获得一块文本。我需要每150个字符插入一个换行符 如果第150个字符不是空格,请在最后一个空格中插入换行符,如果该文本包含换行符,则应重置该计数 我已经用正则表达式尝试过,但是它删除/忽略了文本中的断线,它在单词中间插入了行断裂。 featureText=re.sub.{150},\\1\n,featureText,0,re.DOTALL featureText包含来自api get请求的一些文本 为了简单起见,假设我想每10个字符添加一个换行符。我有文本 My

我从Jira REST Api中获得一块文本。我需要每150个字符插入一个换行符

如果第150个字符不是空格,请在最后一个空格中插入换行符,如果该文本包含换行符,则应重置该计数

我已经用正则表达式尝试过,但是它删除/忽略了文本中的断线,它在单词

中间插入了行断裂。 featureText=re.sub.{150},\\1\n,featureText,0,re.DOTALL featureText包含来自api get请求的一些文本 为了简单起见,假设我想每10个字符添加一个换行符。我有文本

My Television is broken
and that sucks
我现在得到

My Televis
ion is bro
ken and th
at sucks
我想要的是

My
Television
is broken
and that
sucks
编辑:澄清我的问题,让它成为现实世界的失败者。 只有示例使用了10个字符,我真正的问题是使用了150个字符,所以不要担心将一个单词切成两半,我想不会有任何150个字符长的单词。

类似于:

def split_text(text, n):
    for line in text.splitlines():
        while len(line) > n:
           x, line = line[:n], line[n:]
           yield x
        yield line

text = "abcdefghijklmnopqr\nstuvwxyz"

for line in split_text(text, 10):
    print(line)
印刷品:

abcdefghij
klmnopqr
stuvwxyz

我会像这样使用textwrap:

import textwrap

example = textwrap.dedent("""\
    My Television is broken
    and that sucks""")

print '\n'.join(l for line in example.splitlines() 
                  for l in textwrap.wrap(line, width=10))
这导致:

My
Television
is broken
and that
sucks
My
Television
is
and that
sucks
一个更好的例子是:

example = textwrap.dedent("""\
    My Television is
    and that sucks""")
其结果是:

My
Television
is broken
and that
sucks
My
Television
is
and that
sucks

这更好地表明原始行是单独包装的。

不要使用正则表达式。只需使用循环和条件对其进行编码。你是对的。我把这个问题复杂化了,谢谢。我已经澄清了我的问题。谢谢,效果很好,但我发现了一个新问题:它把单词一分为二。我将尝试改进您的想法,只在空白处插入换行符。我已经澄清了我的问题。啊,那么我想您只需要textwrap.fill as@DanD suggestExact:很抱歉,我的问题一开始措辞很糟糕。谢谢你的帮助!这正是我需要的!感谢您帮助一位python初学者!