ad1v7
ad1v7

Reputation: 327

How to split string such that it contains less than n characters with a twist

I have a long string which I want to save to a file. Words are separated by spaces. It is given that the number of words in long string is divisible by 3.

Basically I'm looking for a way to split string into chunks. Each chunk is less than n characters and the number of words in a chunk is also divisible by 3.

e.g.

>>> longstring = "This is a very long string and the sum of words is divisible by three"
>>> len(longstring.split())
>>> 15

say max line length is n=30:

>>>split_string(longstring, 30)
['This is a very long string', 'and the sum of words is', 'divisible by three']

In summary, the rules are:

  1. No line longer than n characters.
  2. A twist is that each new line must contain multiple of 3 words.

So far I tried using textwrap but I don't know how to implement 2.

import textwrap    
textwrap.fill(long_line, width=69)

Upvotes: 1

Views: 177

Answers (1)

Nour Elghareeb
Nour Elghareeb

Reputation: 21

If you are certain that the total number of words in a string will always be divisible by 3, you can do something like this:

import sys
#long string; 84 words; divisible by 3
longString = "The charges are still sealed under orders from a federal judge. Plans were prepared Friday for anyone charged to be into custody as soon as Monday, the sources said. It is unclear what the charges are. A spokesman for the special counsel's office declined to comment. The White House also had no comment, a senior administration official said Saturday morning. A spokesman for the special counsel's office declined to comment. The White House also had no comment, a senior administration official said Saturday morning."
#convert string to list
listOfWords = longString.split()
#list to contain lines
lines = []
#make sure number of words is divisible by 3
if  len(listOfWords) % 3 != 0:
    #exit
    print "words number is not divisible by 3"
    sys.exit()
#keep going until list is empty
while listOfWords:

    i = 0
    line = ""
    #loop for every line
    while True:
        #puts the next 3 words into a string
        temp = " ".join(listOfWords[i:i+3])
        #check new length of line after adding the new 3 words, if it is still less than 70, add the words, otherwise break out of the loop
        if len(line) + len(temp) > 70:
            break
        line += "{} ".format(temp)
        i+=3
    #remove finished words from the list completely
    listOfWords = listOfWords[i:]
    #adds line into result list
    lines.append(line.strip())

#to make sure this works
for line in lines:
    print len(str(line))
    print "Number of words: {}".format(len(line.split()))
    print "number of chars: {}".format(len(line))
    print line
    print "----------------------------------------"

Upvotes: 1

Related Questions