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.