What is the best way to print columns within python. Each of the values that I will be printing will be anything from 1 to 8 characters long. I had found this but wondered if there was any other methods...

http://www.daniweb.com/software-development/python/threads/202023

Thanks,

Dani AI

Generated

Nice thread — pointing to Python’s formatting tools and noting lightweight (whitespace) and library options covers the common choices. For a compact, reusable approach that sits between hand-rolled spacing and a full third‑party table module: compute each column’s display width, build one format string, then print every row with that format. The pattern is small, fast, and lets you pick alignment per column.

A minimal example (rows is a list of sequences):

widths = [max(len(str(x)) for x in col) for col in zip(*rows)]
fmt = "  ".join(f"{{:<{w}}}" for w in widths)   # use > for right-align numbers
for r in rows:
    print(fmt.format(*r))

A few pitfalls and practical tips not called out above:

  • Numbers usually look better right-aligned; use {:>{w}} for those columns and :< for text.
  • For floats, format precision in the column spec (e.g., {:>{w}.2f}) so alignment stays stable.
  • len() measures codepoints, not printed width for CJK or emoji; if you need correct terminal alignment with wide characters, use the wcwidth/wcswidth helper to compute display width instead of len().
  • To avoid overly wide output, query terminal width with shutil.get_terminal_size() and truncate or wrap long cells (textwrap.fill) before formatting.
  • Prefer returning the formatted string from a helper instead of printing directly — easier to test and reuse (logging, files, HTML exports).

If you already have an auto-width function (as did), run it against mixed data: integers, floats, long strings, and a few Unicode samples. Add options for column alignment, padding, and truncation so it stays useful across small scripts and larger output tasks.

Recommended Answers

All 3 Replies

If you want small self contained one, most simplest white space only version has been last in DaniWeb in my post: http://www.daniweb.com/software-development/python/threads/385547/1661150#post1661150

That case was simpler in that way that last number of range is known to be (one of the) longest, normally you would need to use max funcition on value strings.

However it is good idea to use the previously tested general modules mentioned (and in his part developed) by Gribouillis. Actually I have made similar post in StackOverflow about same topic, but Gribouillis method here is nicer than method there: http://stackoverflow.com/questions/3319540/how-to-extend-pretty-print-module-to-tables

I posted a link to module (maybe mentioned also by Gribouillis) those times:
http://code.google.com/p/prettytable/ as solution to the problem (can be installed as with pip also). Actually I have not used that module as the question was more out of curiousity for me.

Also it is not so difficult to build html for table to be shown in web browser. Web browser does all job of formatting and makes the table even resizable.

## http://code.google.com/p/prettytable/wiki/Tutorial
from prettytable import PrettyTable
import webbrowser

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
x.set_field_align("City name", "l") # Left align city names
x.set_padding_width(1) # One space between column edges and contents (default)
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

x.printt()
with open('test.html', 'w') as testfile:
    testfile.write(x.get_html_string())
webbrowser.open('test.html')
commented: nice +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.