-1

I am trying to add a newline after a certain amount of characters and have this working.

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

I would like to modify this so spaces are not counted (newline after the amount of nonspaces).

2 Answers2

0

I've done some research on the topic, and haven't found an elegant solution. There are some cousins to this problem, with solutions involving textwrap and several answers, but nothing that finesses your central problem ...

... which is that you want to count characters in a stripped-and-gutted string, but apply the line feeds to the original. The solution for this would be a somewhat tortured chain to maintain both indices. You'd need to count both letters and spaces; when letter hits a multiple of K, you feed the resulting chunk up the line, from your previous ending point through line[letter_count+space_count].

Frankly, I don't think it's going to be worth the trouble to program, debug, maintain, and (most especially) document for future coders. Just write the loop to iterate through your line. Here's the painfully long version:

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))

Output:

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.
Prune
  • 76,765
  • 14
  • 60
  • 81
0

Like @Prune, I haven't found a elegant way to do it elegantly using any of the existing built-in modules — so here's a(nother) way to do it manually.

It works by creating a list of groups of K non-space characters from the given iterable, and returns that list after processing all the characters in it.

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))

Output:

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.'
martineau
  • 119,623
  • 25
  • 170
  • 301