Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print 5 items in a row on separate lines for a list?

Tags:

python

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
like image 760
Ka-Wa Yip Avatar asked May 26 '15 06:05

Ka-Wa Yip


People also ask

How do I print a list of elements in separate lines?

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.

How do you print on separate lines in Python?

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.

How do I print a list in a row?

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.


2 Answers

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

like image 120
dabhand Avatar answered Nov 02 '22 23:11

dabhand


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
like image 43
ZdaR Avatar answered Nov 03 '22 01:11

ZdaR