Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Print new lines for each item in list

My list contains dates and each time after the date in the same sub-list.

[['2017-01-01', ['List 0', 'List 1', 'List 2']], ['2017-01-02', ['List 0', 'List 1', 'List 2']], ['2017-01-03', ['List 0', 'List 1', 'List 2']], 

I want to make a print statement, which prints for each date a new line and for each item in the sub-list a new line like this:

like in the screenshot

I tried several things, for example:

def printList(self):
        print(*self.dataList, sep='\n')

which prints a new line for each date but I want also a new line for each item in the sublist.

like image 889
Vinz Avatar asked Jun 03 '26 05:06

Vinz


1 Answers

Give pprint from the standard library a try:

import pprint

dataList = [['2017-01-01', ['List 0', 'List 1', 'List 2']], ['2017-01-02', ['List 0', 'List 1', 'List 2']], ['2017-01-03', ['List 0', 'List 1', 'List 2']]]
pprint.pprint(dataList, width=30)

Result:

[['2017-01-01',
  ['List 0',
   'List 1',
   'List 2']],
 ['2017-01-02',
  ['List 0',
   'List 1',
   'List 2']],
 ['2017-01-03',
  ['List 0',
   'List 1',
   'List 2']]]

You may need to play with the width parameter. Also see pprint.pformat().

like image 107
linusg Avatar answered Jun 05 '26 20:06

linusg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!