I have a list of unknown number of items, let\'s say 26. let\'s say
list=[\'a\',\'b\',\'c\',\'d\',\'e\',\'f\',\'g\',\'h\',
\'i\',\'j\',\'k\',\'l\',\'m\',\'n\',\'
You can simple do this by list comprehension: "\n".join(["".join(lst[i:i+5]) for i in xrange(0,len(lst),5)])
the xrange(start, end, interval) here would give a list of integers which are equally spaced at a distance of 5
, then we slice the given list in to small chunks each with length of 5 by using list slicing.
Then the .join() method does what the name suggests, it joins the elements of the list by placing the given character and returns a string.
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
print "\n".join(["".join(lst[i:i+5]) for i in xrange(0,len(lst),5)])
>>> abcde
fghij
klmno
pqrst
uvwxy
z
I think the most cleaner way to write this would be
list=['a','b','c','d','e','f','g','h', 'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in range(0, len(list), 5):
print(*list[i:i+5], sep='')
It needs to invoke for-loop
and join
functions can solve it.
l=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in range(len(l)/5+1):
print "".join(l[i*5:(i+1)*5]) + "\n"
Demo:
abcde
fghij
klmno
pqrst
uvwxy
z
start = 0
for item in list:
if start < 4:
thefile.write("%s" % item)
start = start + 1
else: #once the program wrote 4 items, write the 5th item and two linebreaks
thefile.write("%s\n\n" % item)
start = 0
Just to prove I am really an unreformed JAPH regular expressions are the way to go!
import re
q="".join(lst)
for x in re.finditer('.{,5}',q)
print x.group()
This will work:
n = m = 0
while m < len(l):
m = m+5
print("".join(l[n:m]))
n = m
But I believe there is a more pythonic way to accomplish the task.