Python 如何在大量非空格字符后添加换行符?

Python 如何在大量非空格字符后添加换行符?,python,file-io,character,newline,Python,File Io,Character,Newline,我正在尝试在一定数量的字符后添加一个换行符,并使其正常工作 outfile.write('\n'.join(line[i:i+K] for i in range(0,len(line), K))) 我想对此进行修改,以便不计算空格(在非空格数量之后换行)。我对该主题做了一些研究,但没有找到一个优雅的解决方案。这个问题有一些近亲,解决方案涉及和,但没有什么能解决你的中心问题 。。。也就是说,您希望对剥离和删除的字符串中的字符进行计数,但对原始字符串应用换行符。解决这一问题的方法是使用一条有点扭曲

我正在尝试在一定数量的字符后添加一个换行符,并使其正常工作

outfile.write('\n'.join(line[i:i+K] for i in range(0,len(line), K)))

我想对此进行修改,以便不计算空格(在非空格数量之后换行)。

我对该主题做了一些研究,但没有找到一个优雅的解决方案。这个问题有一些近亲,解决方案涉及和,但没有什么能解决你的中心问题

。。。也就是说,您希望对剥离和删除的字符串中的字符进行计数,但对原始字符串应用换行符。解决这一问题的方法是使用一条有点扭曲的链来维护这两个索引。你需要数一数字母和空格;当
letter
点击
K
的倍数时,您将生成的从上一个端点向上送入行[letter\u count+space\u count]

坦率地说,我认为为未来的程序员编程、调试、维护和(尤其是)编写文档是不值得的。只需编写循环来遍历您的行。以下是令人痛苦的长版本:

line = "Now is the time for all good parties to come to the aid of man." + \
       "  It was the best of times, it was the worst of times."
K = 20

slugs = []
left = 0
count = 0
for idx, char in enumerate(line):
    if char != ' ':
        count += 1
    if count == K:
        count = 0
        slugs.append(line[left: idx+1])
        left = idx+1

slugs.append(line[left:])
print ('\n'.join(slugs))
输出:

Now is the time for all go
od parties to come to the
 aid of man.  It was the bes
t of times, it was the wor
st of times.
I am t'
'ryin'
'g to a'
'dd a n'
'ewli'
'ne af'
'ter a'
' cert'
'ain a'
'moun'
't of c'
'hara'
'cter'
's.'

像@Prune一样,我还没有找到一种优雅的方法来使用任何现有的内置模块优雅地完成它——所以这里有一种(另一种)手动完成的方法

它的工作原理是从给定的iterable中创建一组K个非空格字符,并在处理其中的所有字符后返回该列表

def grouper(iterable, K):
    nonspaced = []
    group = []
    count = 0
    for ch in iterable:
        group.append(ch)
        if ch != ' ':
            count += 1
            if count == 4:
                nonspaced.append(''.join(group))
                group = []
                count = 0
    if group:
        nonspaced.append(''.join(group))

    return nonspaced


K = 4
line = "I am trying to add a newline after a certain amount of characters."
for group in grouper(line, K):
    print(repr(group))
输出:

Now is the time for all go
od parties to come to the
 aid of man.  It was the bes
t of times, it was the wor
st of times.
I am t'
'ryin'
'g to a'
'dd a n'
'ewli'
'ne af'
'ter a'
' cert'
'ain a'
'moun'
't of c'
'hara'
'cter'
's.'

如果我读对了,你可以对列表中的I(filter(lambda x:x!=“”,range(0,len(line),K)))说类似于
@RobertHarvey没有工作,运行时没有错误,但没有效果。这仍然是我将采用的方法。