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...

The steps are as follows:

  1. The shutil.get_terminal_size function can give guidance on the terminal window size and provide a fallback for cases where it's not available. We will adapt the maketable function from the Aligning text recipe of Chapter 2Text Management to account for terminal size:
import shutil
import textwrap, itertools

def maketable(cols):
    term_size = shutil.get_terminal_size(fallback=(80, 24))
    colsize = (term_size.columns // len(cols)) - 3
    if colsize < 1:
        raise ValueError('Column too small')
    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. Now it is possible to print any text in multiple columns ...
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