Create Nice Column Output in Python

Create nice column output in python

data = [['a', 'b', 'c'], ['Create Nice Column Output in Pythonaa', 'b', 'c'], ['a', 'bb', 'c']]

col_width = max(len(word) for row in data for word in row) + 2 # padding
for row in data:
print "".join(word.ljust(col_width) for word in row)

a b c
Create Nice Column Output in Pythonaa b c
a bb c

What this does is calculate the longest data entry to determine the column width, then use .ljust() to add the necessary padding when printing out each column.

How to Print Pretty String Output in Python

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.

Line up columns of numbers (print output in table format)

Here is a simple, self-contained example that shows how to format variable column widths:

data = '''\
234 127 34 23 45567
23 12 4 4 45
23456 2 1 444 567'''

# Split input data by row and then on spaces
rows = [ line.strip().split(' ') for line in data.split('\n') ]

# Reorganize data by columns
cols = zip(*rows)

# Compute column widths by taking maximum length of values per column
col_widths = [ max(len(value) for value in col) for col in cols ]

# Create a suitable format string
format = ' '.join(['%%%ds' % width for width in col_widths ])

# Print each row using the computed format
for row in rows:
print format % tuple(row)

which outputs:

  234 127 34  23 45567
23 12 4 4 45
23456 2 1 444 567

String formatting: Columns in line

str.format() is making your fields left aligned within the available space. Use alignment specifiers to change the alignment:

'<' Forces the field to be left-aligned within the available space (this is the default for most objects).

'>' Forces the field to be right-aligned within the
available space (this is the default for numbers).

'=' Forces the padding to be placed after the
sign (if any) but before the digits. This is used for printing fields
in the form ‘+000000120’. This alignment option is only valid for
numeric types.

'^' Forces the field to be centered within the
available space.

Here's an example (with both left and right alignments):

>>> for args in (('apple', '$1.09', '80'), ('truffle', '$58.01', '2')):
... print '{0:<10} {1:>8} {2:>8}'.format(*args)
...
apple $1.09 80
truffle $58.01 2

How To Print Separate Strings In Good Looking Columns In Python?

Fix the width for the first column in the print function. Currently you're only doing that for the second column.

import os

def print_size(directory_path):
all_files_in_directory = os.listdir(directory_path)
for file in all_files_in_directory:
print("{: >30} {: >10}".format(file, str(int(os.path.getsize(directory_path + file) / 1024)) + " KB"))

print_size('./')

Printing Lists as Tabular Data

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.

Printing string with two columns

You can use format and mention fix spaces between columns

'{0:10}  {1}'.format(s1, s2)

Old Style formatting

'%-10s' '%s' % (s1,s2)


Related Topics



Leave a reply



Submit