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','o','p','q','r','s','t','u','v','w','x','y','z']
How to print like this:
abcde
fghij
klmno
pqrst
uvwxy
z
? Thank you very much. Attempt:
start = 0
for item in list:
if start < 5:
thefile.write("%s" % item)
start = start + 5
else:
thefile.write("%s" % item)
start = 0
Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.
The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.
1 Answer. You can add the parameter "end" to the print statement. The value of "end" should be a space(" "). Then print will put all elements in a row with a space between them.
for i, a in enumerate(A):
print a,
if i % 5 == 4:
print "\n"
Another alternative, the comma after the print means there is no newline character
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With