Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

How to do it...

Here are the steps for this recipe:

  1. The textwrap module once combined with the features of the str object can help us achieve the expected result. First we need the content of the columns we want to print:
cols = ['hello world', 
        'this is a long text, maybe longer than expected, surely long enough', 
        'one more column']
  1. Then we need to fix the size of a column:
COLSIZE = 20
  1. Once those are ready, we can actually implement our indentation function:
import textwrap, itertools

def maketable(cols):
    return 'n'.join(map(' | '.join, itertools.zip_longest(*[
        [s.ljust(COLSIZE) for s in textwrap.wrap(col, COLSIZE)] for col in cols
    ], fillvalue=' '*COLSIZE)))
  1. Then we can properly print any table:
>>> print(maketable(cols)) hello ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content