-2

I have a list of integer

a=[1,2,3,4,5,6,7,8,9]

and i must create a string with the integers separated by spaces and every five number i must add a '\n'

string='1 2 3 4 5\n6 7 8 9\n\n'


I have tried with a join like that:

string=' '.join(a)

but i don't know how to add '\n' with a condition.

1 Answers1

1

You can use generator expressions to output the list in chunks for joining:

print('\n'.join(' '.join(map(str, a[i: i + 5])) for i in range(0, len(a), 5)))

This outputs:

1 2 3 4 5
6 7 8 9
blhsing
  • 91,368
  • 6
  • 71
  • 106