Sabba
Sabba

Reputation: 561

Python while, continue loops

My input file is one sentence per line. Let's say it looks like:

A
B
C
D
E
F

Desired output is:

::NewPage::
A
B
::NewPage::
C
D
::NewPage::
E
F

I know that I should be using a while loop but not sure how to?

Upvotes: 0

Views: 456

Answers (3)

hitokiri82
hitokiri82

Reputation: 71

I dont know if this might bother the gods of the PEP-8.

But a language agnostic alternative (understandable by a more generic audience) might be:

items = ["A", "B", "C", "D", "E"]
out = []

for i,item in enumerate(items):
    if i%2 == 0:
        out.append("::New Page::")
    out.append(item)

Edit: this is what happens when you dont check if there's a new answer before finishing writing yours. My answer is basicallly the same as cdarke's.

Upvotes: 2

cdarke
cdarke

Reputation: 44424

Like this? Tested on Python 3.3:

i = 0
page_size = 2
lines = []

for line in open("try.txt"):
    lines.append(line)
    i += 1
    if i % page_size == 0:
        print("::NewPage::")
        print("".join(lines),end="")
        i = 0
        lines = []

Upvotes: 1

Gareth Latty
Gareth Latty

Reputation: 89097

You don't need a while loop here - look at the grouper recipe in itertools.

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

Note that you will need a slightly different version if you are using 2.x.

E.g:

items = ["A", "B", "C", "D", "E"]
for page in grouper(2, items):
    print("::NewPage::")
    for item in page:
        if item is not None:
            print(item)

Which produces:

::NewPage::
A
B
::NewPage::
C
D
::NewPage::
E

If you need None values, you can use a sentinel object.

Upvotes: 4

Related Questions