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?
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?
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.
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.