Nick
Nick

Reputation: 10499

Print formatted list

I have a list:

l = [i for i in range(9)]

and I need to format its string representation as follows:

'{0}{1}{2}\n{3}{4}{5}\n{6}{7}{8}'.format(l[0], l[1], l[2], l[3], l[4], l[5], l[6], l[7], l[8])

Is there a more elegant/brief way to do such a thing?

I thought of something like the following:

'{0}{1}{2}\n{3}{4}{5}\n{6}{7}{8}'.format([l[i] for i in range(9)])

But it seems it doesn't work. Any alternatives?

Upvotes: 0

Views: 62

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55499

FWIW, Here's a Python 2 style version:

L = list('abcdefghi')
print '\n'.join([''.join(u) for u in zip(*[L[i::3] for i in (0, 1, 2)])])

Upvotes: 0

elyase
elyase

Reputation: 41003

You probably want to do argument unpacking:

'{0}{1}{2}\n{3}{4}{5}\n{6}{7}{8}'.format(*l)

Take a look here for more details.

Upvotes: 2

Related Questions