0

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?

1
  • 2
    So where exactly do you have problems? Have you tried anything? Commented Oct 11, 2012 at 12:30

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget to note the Python 2 recipes in case @Sabba is using that version. docs.python.org/library/itertools.html#recipes
@zigg I was just adding that note in.
2

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.

Comments

1

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 = []

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.