0
Sentence = "the heart was made to be broken"

How to split sentence for displaying in separate lines by using Python? (4 words per line)

Line1: the heart was made
Line2: to be broken

Any advice?

ThanaDaray
  • 1,613
  • 5
  • 21
  • 28

5 Answers5

6
  1. Turn the sentence into a list of words.
  2. Partition the list into chunks of 4 words.
  3. Combine the partitions into lines.
Community
  • 1
  • 1
Matt Ball
  • 344,413
  • 96
  • 627
  • 693
2

Try this:

s = 'the heart was made to be broken'

for i, word in enumerate(s.split(), 1):
    if i % 4:
        print word,
    else:
        print word

> the heart was made
> to be broken
Óscar López
  • 225,348
  • 35
  • 301
  • 374
0

Here's a solution:

import math

def fourword(s):
    words = s.split()
    fourcount = int(math.ceil(len(words)/4.0))
    for i in range(fourcount):
        print " ".join(words[i*4:(i+1)*4])

if __name__=="__main__":
    fourword("This is a test of fourword")
    fourword("And another test of four")

The output is:

>python fourword.py 
This is a test
of fourword
And another test of
four
craigmj
  • 4,549
  • 2
  • 17
  • 21
0

Let me explain the solution for this problem which use itertools module. When you're trying to deal with sequence, be it a list or string or any other iterable, it's generally a good first step to take a look at itertools module from standard library

from itertools import count, izip, islice, starmap

# split sentence into words
sentence = "the heart was made to be broken".split()
# infinite indicies sequence -- (0, 4), (4, 8), (8, 12), ...
indicies = izip(count(0, 4), count(4, 4)) 
# map over indices with slicing
for line in starmap(lambda x, y: sentence[x:y], indicies):
    line = " ".join(line)
    if not line:
        break
    print line
andreypopp
  • 6,757
  • 5
  • 25
  • 26
0

Generic function:

from itertools import count, groupby

def split_lines(sentence, step=4):
    c = count()
    chunks = sentence.split()
    return [' '.join(g) for k, g in groupby(chunks, lambda i: c.next() // step)]

Which you can use like this:

>>> sentence = "the heart was made to be broken"
>>> split_lines(sentence)
['the heart was made', 'to be broken']
>>> split_lines(sentence, 5)
['the heart was made to', 'be broken']
>>> split_lines(sentence, 2)
['the heart', 'was made', 'to be', 'broken']

With the result you can do anything you want (including printing):

>>> for line in split_lines(sentence):
...     print line
...     
the heart was made
to be broken
rubik
  • 8,230
  • 7
  • 58
  • 87
  • 1
    Can you do this for a number of characters? –  Jul 27 '17 at 21:07
  • @BenWebb Yes, you can use a slightly modified version of the `split_lines` function above. Instead of operating on `chunks = sentence.split()` you operate on `sentence` directly. – rubik Jul 28 '17 at 07:31