Python Forum
printing text tables with consistent width
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
printing text tables with consistent width
#3
Here's a simple example I whipped up:

def table(rows):
	max_widths = []
	for column in zip(*rows):
		max_widths.append(max([len(text) for text in column]))
	template = '  '.join(['{{:<{}}}'.format(width) for width in max_widths])
	return '\n'.join([template.format(*row) for row in rows])

knights = [['Sir Lancelot', 'The Holy Grail', 'Blue'],
	['Sir Robin', 'The Holy Grail', "I don't know that."],
	['Sir Galahad', 'The Grail', 'Blue. No, yel...'],
	['King Arthur', 'The Holy Grail', 'What do you mean?']]

print(table(knights))
Output:
Sir Lancelot The Holy Grail Blue Sir Robin The Holy Grail I don't know that. Sir Galahad The Grail Blue. No, yel... King Arthur The Holy Grail What do you mean?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
RE: printing text tables with consistent width - by ichabod801 - Jun-30-2018, 04:10 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python code to set column width 1418 11 1,539 Jan-20-2024, 07:20 AM
Last Post: Pedroski55
  Fixed colum width for rowLabels i Matplotlib pandabay 0 453 Jun-10-2023, 03:40 PM
Last Post: pandabay
  Setup host for consistent data transfer to client via TCP Gustav97 0 728 Jun-27-2022, 07:33 PM
Last Post: Gustav97
  Consistent error Led_Zeppelin 1 1,673 Dec-20-2021, 01:39 AM
Last Post: snippsat
  width of Unicode character Skaperen 6 2,819 Sep-27-2021, 12:41 AM
Last Post: Skaperen
  image.thumbnail(width, height) not working PCesarano 2 3,497 Apr-08-2021, 06:09 PM
Last Post: PCesarano
  Error printing colored text julio2000 0 1,518 Feb-02-2020, 07:04 PM
Last Post: julio2000
  How can I get the width of a string in Python? aquerci 14 16,441 May-27-2019, 06:00 PM
Last Post: heiner55
  fixed width numbers Skaperen 15 8,865 May-27-2019, 09:42 AM
Last Post: Skaperen
  Printing lines in a basic text file Drone4four 6 3,938 Aug-16-2018, 03:10 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020