UberNate
UberNate

Reputation: 2399

How to print strings from a list in sequence in Python?

Suppose a list: s = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]

I understand how to print every item in the list:

for i in s:
    print (i)

which gives:

A
B
C
D
E
F
G
H
I
J

But suppose I want to split the printing in terms of n. So if n = 3:

A
B
C

D
E
F

G
H
I

J

These are my attempts:

k = 0
for i in s:
    while k < n:
        k += 1
        print (i)

and

k = 0
while k < n:
    for i in s:
        print (i)
    k += 1

I understand that my attempts are way off, but I can't seem to get it. I know you can create sub-lists in terms of n and solve it that way, but is there a way you can do this otherwise?

Upvotes: 0

Views: 1165

Answers (2)

dawg
dawg

Reputation: 103744

>>> s = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
>>> n=3
>>> print('\n\n'.join(['\n'.join(s[i:i+n]) for i in range(0,len(s),n)]))
A
B
C

D
E
F

G
H
I

J

Upvotes: 0

eaxix
eaxix

Reputation: 78

k = 0
for i in s:
    if k == n-1:
       print i + '\n'
       k = 0
    else:
        print i
        k += 1

Upvotes: 1

Related Questions