Standard Python string formatting may suffice.

# assume that your data rows are tuples
template = "{0:8}|{1:10}|{2:15}|{3:7}|{4:10}" # column widths: 8, 10, 15, 7, 10
print template.format("CLASSID", "DEPT", "COURSE NUMBER", "AREA", "TITLE") # header
for rec in your_data_source: 
  print template.format(*rec)

Or

# assume that your data rows are dicts
template = "{CLASSID:8}|{DEPT:10}|{C_NUM:15}|{AREA:7}|{TITLE:10}" # same, but named
print template.format( # header
  CLASSID="CLASSID", DEPT="DEPT", C_NUM="COURSE NUMBER", 
  AREA="AREA", TITLE="TITLE"
) 
for rec in your_data_source: 
  print template.format(**rec)

Play with alignment, padding, and exact format specifiers to get best results.

Answer from 9000 on Stack Overflow
🌐
PyPI
pypi.org › project › tabulate
tabulate · PyPI
Pretty-print tabular data in Python, a library and a command-line utility. ... printing small tables without hassle: just one function call, formatting is guided by the data itself · authoring tabular data for lightweight plain-text markup: multiple output formats suitable for further editing or transformation · readable presentation of mixed textual and numeric data: smart column alignment, configurable number formatting, alignment by a decimal point
      » pip install tabulate
    
Published   Mar 04, 2026
Version   0.10.0
🌐
Delft Stack
delftstack.com › home › howto › python › python print column alignment
How to Print With Column Alignment in Python | Delft Stack
February 22, 2025 - Learn how to align columns in Python using print(), format(), f-strings, and libraries like tabulate and pandas. This guide covers techniques for formatting tabular data, ensuring clean and readable output. Perfect for Python developers!
Discussions

How to Print "Pretty" String Output in Python - Stack Overflow
The example output seems to match what you are requesting. Or this table indentation method. I haven't used either, but they were in the first few result of googling "python pretty print table" ... If you need to print an aligned table without a header, see here: How to print a list of dicts ... More on stackoverflow.com
🌐 stackoverflow.com
How to get the columns to align perfectly on a table?
Tabs end up a horrible way to format output. You could rely on str.format() to assemble strings with alignment and (field) widths. first = ['Anna', 'Beatrice', 'Charles', 'David', 'Emma'] last = ['Anderson', 'Brown', 'Clark', 'Daniels', 'Edwards'] major = ['Mathematics', 'Data Science', 'Biology', 'Chemistry', 'Computer Science'] credits = [110, 83, 64, 35, 104] gpa = [3.56, 3.24, 3.87, 2.83, 3.61] row = "{:<20} {:<20} {:<20} {:>10} {:>7.2f}" header_row = "{:<20} {:<20} {:<20} {:>10} {:>7}" headers = "First Last Major Credits GPA".split() print(header_row.format(*headers)) print("-" * 81) for first_, last_, major_, credits_, gpa_ in zip(first, last, major, credits, gpa): print(row.format(first_, last_, major_, credits_, gpa_)) Now, constructing the original data better would make this much easier, but this should work, resulting in: First Last Major Credits GPA --------------------------------------------------------------------------------- Anna Anderson Mathematics 110 3.56 Beatrice Brown Data Science 83 3.24 Charles Clark Biology 64 3.87 David Daniels Chemistry 35 2.83 Emma Edwards Computer Science 104 3.61 Libraries like Tabulate make this even easier, for down the road. More on reddit.com
🌐 r/learnpython
5
3
May 15, 2022
Python spacing and aligning strings - Stack Overflow
I am trying to add spacing to align text in between two strings vars without using " " to do so Trying to get the text to look like this, with the second column being aligned. Loca... More on stackoverflow.com
🌐 stackoverflow.com
python - Printing Lists as Tabular Data - Stack Overflow
If you want your left heading right aligned just change this call: ... The link seems to be dead. Do you have an updated link? 2021-11-16T19:35:48.483Z+00:00 ... @jvriesem: the internet archive has the page: pretty-printing-a-table-in-python 2022-08-23T06:28:29.783Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
🌐
LearnPython.com
learnpython.com › blog › print-table-in-python
How to Pretty-Print Tables in Python | LearnPython.com
From here, you can simply print() the table to visualize it in ASCII form, or you can use the many available methods to modify and format tabular data. To add a single row, there’s the add_row() method; to add a column, use the add_column() method. The latter has two required arguments: a string to define fieldname and a list or tuple as column. You can also define the horizontal and vertical alignments as shown in the following example:
Top answer
1 of 5
69

Standard Python string formatting may suffice.

# assume that your data rows are tuples
template = "{0:8}|{1:10}|{2:15}|{3:7}|{4:10}" # column widths: 8, 10, 15, 7, 10
print template.format("CLASSID", "DEPT", "COURSE NUMBER", "AREA", "TITLE") # header
for rec in your_data_source: 
  print template.format(*rec)

Or

# assume that your data rows are dicts
template = "{CLASSID:8}|{DEPT:10}|{C_NUM:15}|{AREA:7}|{TITLE:10}" # same, but named
print template.format( # header
  CLASSID="CLASSID", DEPT="DEPT", C_NUM="COURSE NUMBER", 
  AREA="AREA", TITLE="TITLE"
) 
for rec in your_data_source: 
  print template.format(**rec)

Play with alignment, padding, and exact format specifiers to get best results.

2 of 5
11
class TablePrinter(object):
    "Print a list of dicts as a table"
    def __init__(self, fmt, sep=' ', ul=None):
        """        
        @param fmt: list of tuple(heading, key, width)
                        heading: str, column label
                        key: dictionary key to value to print
                        width: int, column width in chars
        @param sep: string, separation between columns
        @param ul: string, character to underline column label, or None for no underlining
        """
        super(TablePrinter,self).__init__()
        self.fmt   = str(sep).join('{lb}{0}:{1}{rb}'.format(key, width, lb='{', rb='}') for heading,key,width in fmt)
        self.head  = {key:heading for heading,key,width in fmt}
        self.ul    = {key:str(ul)*width for heading,key,width in fmt} if ul else None
        self.width = {key:width for heading,key,width in fmt}

    def row(self, data):
        return self.fmt.format(**{ k:str(data.get(k,''))[:w] for k,w in self.width.iteritems() })

    def __call__(self, dataList):
        _r = self.row
        res = [_r(data) for data in dataList]
        res.insert(0, _r(self.head))
        if self.ul:
            res.insert(1, _r(self.ul))
        return '\n'.join(res)

and in use:

data = [
    {'classid':'foo', 'dept':'bar', 'coursenum':'foo', 'area':'bar', 'title':'foo'},
    {'classid':'yoo', 'dept':'hat', 'coursenum':'yoo', 'area':'bar', 'title':'hat'},
    {'classid':'yoo'*9, 'dept':'hat'*9, 'coursenum':'yoo'*9, 'area':'bar'*9, 'title':'hathat'*9}
]

fmt = [
    ('ClassID',       'classid',   11),
    ('Dept',          'dept',       8),
    ('Course Number', 'coursenum', 20),
    ('Area',          'area',       8),
    ('Title',         'title',     30)
]

print( TablePrinter(fmt, ul='=')(data) )

produces

ClassID     Dept     Course Number        Area     Title                         
=========== ======== ==================== ======== ==============================
foo         bar      foo                  bar      foo                           
yoo         hat      yoo                  bar      hat                           
yooyooyooyo hathatha yooyooyooyooyooyooyo barbarba hathathathathathathathathathat
🌐
Reddit
reddit.com › r/learnpython › how to get the columns to align perfectly on a table?
r/learnpython on Reddit: How to get the columns to align perfectly on a table?
May 15, 2022 -

I'm having a little trouble printing my lists onto a table, to where each column lines up with the very first row.

Below is my work so far;

Here are my lists:

first = ['Anna', 'Beatrice', 'Charles', 'David', 'Emma']

last = ['Anderson', 'Brown', 'Clark', 'Daniels', 'Edwards']

major = ['Mathematics', 'Data Science', 'Biology', 'Chemistry', 'Computer Science']

credits = [110, 83, 64, 35, 104]

gpa = [3.56, 3.24, 3.87, 2.83, 3.61]

_____________________________________________________________________________

and here is where I tried printing said list a la table mode:

print('First\tLast\tMajor\tCredits\tGPA')

print('-' * 56)

for i in range(0,4):

print(first[i], '\t', last[i], '\t', major[i], '\t', credits[i], '\t', gpa[i])

______________________________________________________________________________

I wish I can show the out put, but the copy paste won't work correctly. Basically what is happening is the top line where "First, Last, Major, etc) seems to be all squished together.

The elements of the lists are all messed up as well, including but not limited to some of the elements being in entirely incorrect columns.

If you can let me know if I may be overlooking anything, thank you!

🌐
LabEx
labex.io › tutorials › python-how-to-align-output-in-python-printing-418802
How to align output in Python printing | LabEx
Tables are a common way to display structured data in a readable format, and proper alignment is crucial for presenting tabular information effectively. Let's start by creating a simple table using fixed width columns. Create a new file named simple_table.py in the /home/labex/project directory: ## simple_table.py print("Simple Fixed-Width Table") print("-" * 50) ## Define some data header = ["Name", "Age", "City", "Profession"] data = [ ["John Smith", 34, "New York", "Doctor"], ["Sarah Johnson", 28, "San Francisco", "Engineer"], ["Michael Brown", 42, "Chicago", "Teacher"], ["Emily Davis", 31, "Boston", "Scientist"] ] ## Print header print(f"{header[0]:<20} {header[1]:<8} {header[2]:<15} {header[3]:<15}") print("-" * 60) ## Print rows for row in data: print(f"{row[0]:<20} {row[1]:<8} {row[2]:<15} {row[3]:<15}")
🌐
EyeHunts
tutorial.eyehunts.com › home › python print table align | example code
Python print table align | Example code - Tutorial - By EyeHunts
December 16, 2022 - Using the .format approach, you could use padding to align all of your strings. You can also use tabulate module for it. Simple example code text formatting rows in Python. table_data = [ ['a', 'b', 'c'], ['ABC', 'b', 'c'], ['a', 'XYZ', 'c'] ] for row in table_data: print("{: >5} {: >5} {: >5}".format(*row))
🌐
Scientifically Sound
scientificallysound.org › 2016 › 10 › 17 › python-print3
Take control of your Python print() statements: part 3 | Scientifically Sound
November 17, 2021 - In the last post, we learned how to control the precision of the number we print as well as the number of spaces these numbers take up. The last thing we need to learn to output nice data tables is how to align text and numbers when we use .format(). We previously learned to specify the number of spaces allocated to the inputs we provide to .format(). Now we will see that we can tell Python how we want to align our text or numbers in these spaces.
Find elsewhere
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 439187 › aligning-columns-in-a-table
python - Aligning Columns in a table? [SOLVED] | DaniWeb
November 5, 2012 - def format_table(cells, rows, cols, aligns, sep="\t "): # aligns like ["L","C","R"] for each column pads = {"L": str.ljust, "R": str.rjust, "C": str.center} aligns = [a.upper() if a.upper() in pads else "L" for a in aligns] # compute max width for each column widths = [0]*cols for r in range(rows): for c in range(cols): i = r*cols + c val = "" if i >= len(cells) else str(cells[i]) widths[c] = max(widths[c], len(val)) # build lines lines = [] for r in range(rows): row = [] for c in range(cols): i = r*cols + c val = "" if i >= len(cells) else str(cells[i]) row.append(pads[aligns[c]](val, widths[c])) lines.append(sep.join(row)) return "\n".join(lines) # Example: words = ["help","I","don't","know","how","to","do","these","tables."] print(format_table(words, rows=3, cols=3, aligns=["L","C","R"]))
🌐
Readthedocs
ptable.readthedocs.io › en › latest › tutorial.html
Tutorial — PTable 0.9.0 documentation
You can change the alignment of all the columns in a table at once by assigning a one character string to the align attribute.
🌐
ZetCode
zetcode.com › python › prettytable
Python PrettyTable - generating tables in Python with PrettyTable
PrettyTable is a Python library for generating simple ASCII tables. It was inspired by the ASCII tables used in the PostgreSQL shell psql. We can control many aspects of a table, such as the width of the column padding, the alignment of text, or the table border.
Top answer
1 of 16
1041

There are some light and useful python packages for this purpose:

1. tabulate

https://pypi.python.org/pypi/tabulate

from tabulate import tabulate
print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']))
Name      Age
------  -----
Alice      24
Bob        19

tabulate has many options to specify headers and table format.

print(tabulate(
    [['Alice', 24], ['Bob', 19]],
    headers=['Name', 'Age'],
    tablefmt='orgtbl'))
| Name   |   Age |
|--------+-------|
| Alice  |    24 |
| Bob    |    19 |

2. PrettyTable

https://pypi.python.org/pypi/PrettyTable

from prettytable import PrettyTable
t = PrettyTable(['Name', 'Age'])
t.add_row(['Alice', 24])
t.add_row(['Bob', 19])
print(t)
+-------+-----+
|  Name | Age |
+-------+-----+
| Alice |  24 |
|  Bob  |  19 |
+-------+-----+

PrettyTable has options to read data from csv, html, sql database. Also you are able to select subset of data, sort table and change table styles.

3. texttable

https://pypi.python.org/pypi/texttable

from texttable import Texttable
t = Texttable()
t.add_rows([['Name', 'Age'], ['Alice', 24], ['Bob', 19]])
print(t.draw())
+-------+-----+
| Name  | Age |
+=======+=====+
| Alice | 24  |
+-------+-----+
| Bob   | 19  |
+-------+-----+

with texttable you can control horizontal/vertical align, border style and data types.

4. termtables

https://github.com/nschloe/termtables

import termtables as tt

string = tt.to_string(
    [["Alice", 24], ["Bob", 19]],
    header=["Name", "Age"],
    style=tt.styles.ascii_thin_double,
    # alignment="ll",
    # padding=(0, 1),
)
print(string)
+-------+-----+
| Name  | Age |
+=======+=====+
| Alice | 24  |
+-------+-----+
| Bob   | 19  |
+-------+-----+

with texttable you can control horizontal/vertical align, border style and data types.

Other options

  • terminaltables - Easily draw tables in terminal/console applications from a list of lists of strings. Supports multi-line rows.
  • asciitable can read and write a wide range of ASCII table formats via built-in Extension Reader Classes.
2 of 16
324

Some ad-hoc code:

row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
    print(row_format.format(team, *row))

This relies on str.format() and the Format Specification Mini-Language.

Top answer
1 of 2
2

I highly suggest you to convert your Table into a pandas Dataframe. If you do so, obtaining a tabular representation of your table is easy using to_markdown:

# Generating a test table in pandas
df  = pd.DataFrame({'Column_2': {'test': 'Craig', 'test2': 'Bob', 'test3': 'Bill'},
 'Column_3': {'test': False, 'test2': False, 'test3': False},
 'Column_4': {'test': '[]', 'test2': '[]', 'test3': '[]'},
 'Column_5': {'test': '<function Foo at 0x7f9f898a0e18>',
  'test2': '<function Bar at 0x7f9f881ae730>',
  'test3': '<function Baz at 0x7f9f881ae7b8>'}})
df.index.name = 'Column_1'

# Printing the table in a nice tabular way:
print(df.to_markdown())
| Column_1   | Column_2    | Column_3    | Column_4    | Column_5                         |
|:-----------|:------------|:------------|:------------|:---------------------------------|
| test       | Craig       | False       | []          | <function Foo at 0x7f9f898a0e18> |
| test2      | Bob         | False       | []          | <function Bar at 0x7f9f881ae730> |
| test3      | Bill        | False       | []          | <function Baz at 0x7f9f881ae7b8> |

In general, all table operations are supported by pandas, which is why it is not recommended to build your own Table structure (unless this is part of some learning course).

2 of 2
2

Use a well-known Python package to print in tabular format. For example, you may use prettytable. You can install it with the command: pip install prettytable.

>>> from prettytable import PrettyTable
>>> t = PrettyTable(hdrs)
>>>
>>> headers = ("Column_1", "Column_2", "Column_3", "Column_4", "Column_5")
>>> t = PrettyTable(headers)
>>> t.add_row(("test","Craig",False,[], 'Foo'))
>>> t.add_row(("test2","Bob",False,[], 'Bar'))
>>> t.add_row(("test3","Bill",False,[], 'Baz'))
>>> print(t)
+-----------+-----------+-----------+-----------+-----------+
| Column_1  | Column_2  | Column_3  | Column_4  | Column_5  |
+-----------+-----------+-----------+-----------+-----------+
|    test   |   Craig   |   False   |     []    |    Foo    |
|   test2   |    Bob    |   False   |     []    |    Bar    |
|   test3   |    Bill   |   False   |     []    |    Baz    |
+-----------+-----------+-----------+-----------+-----------+
🌐
Reddit
reddit.com › r/learnpython › python multiplication table alignment
r/learnpython on Reddit: Python multiplication table alignment
December 15, 2022 -

I want to construct a multiplication table and have the code below. however, when it prints out the code, the rows and columns aren't aligned correctly. How can I get them exactly aligned and in their right positions in the simplest way possible for me to grasp as a beginner?

rows= int(input("How many rows?: "))

columns= int(input("How many columns?: "))

for row in range(1, rows+1):
   for col in range(1,columns+1):
      print(row * col, end="  ")
print()

I searched the internet and came across this video regarding the multiplication table in Python, but I'd want to have a second perspective.

Thank you very much!

🌐
Replit
replit.com › home › discover › how to print a table in python
How to print a table in Python | Replit
March 10, 2026 - You can embed expressions directly inside curly braces {} within a string that's prefixed with an f. Learn more about using f-strings in Python. ... You explicitly print the headers first, accessing each one by its index, like headers[0]. Then, you loop through the data rows and apply the same logic, using indices like row[0] for each cell. The alignment syntax is identical to the .format() method, making this an intuitive upgrade for cleaner code.
🌐
PyPI
pypi.org › project › prettytable
prettytable · PyPI
For options that can be set individually for each column (align, valign, custom_format, max_width, min_width, int_format, float_format, none_format) you can either set a value, that applies to all columns or set a dict with column names and individual values. ... If you want to print your table with a different style several times, you can set your option for the long term just by changing the appropriate attributes.
      » pip install prettytable
    
Published   Nov 14, 2025
Version   3.17.0
🌐
DataCamp
datacamp.com › tutorial › python-tabulate
Python Tabulate: A Full Guide | DataCamp
September 5, 2024 - print(tabulate(df, headers='keys', tablefmt='grid')) Table output using grid formatting style in Python tabulate() function. Image by Author. The tabulate library offers advanced features that allow you to customize the appearance of complex tables. Let us discuss some of these features. The tabulate library offers different ways to customize table appearance, such as adjusting alignment...