ThanaDaray
ThanaDaray

Reputation: 1693

Python: Is it possible to split sentence into two line?

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?

Upvotes: 0

Views: 4250

Answers (5)

rubik
rubik

Reputation: 9104

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

Upvotes: 0

Óscar López
Óscar López

Reputation: 235984

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

Upvotes: 2

andreypopp
andreypopp

Reputation: 6953

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

Upvotes: 0

craigmj
craigmj

Reputation: 5067

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

Upvotes: 0

Related Questions