Skip to content

Latest commit

 

History

History
39 lines (23 loc) · 1.27 KB

20231207123339.md

File metadata and controls

39 lines (23 loc) · 1.27 KB

How to capture the Zen of Python (and redirect standard output)?

How to get the Zen of Python into one or more variables while muting "import this"'s default behavior of printing to standard output?

You can use a context manager, specifically redirect_stdout() from the contextlib module:

This is what I came up with:

import codecs
import contextlib
import io

SHORT_TITLE = "Zen of Python {number}: {title} #pythonic #development"

with contextlib.redirect_stdout(io.StringIO()):
    import this

import_this_output = codecs.decode(this.s, 'rot13')

for i, title in enumerate(import_this_output.splitlines()[2:], start=1):
    print(SHORT_TITLE.format(number=i, title=title))
  1. Use contextlib.redirect_stdout(... to mute console output of the "import this" statement.

  2. Use the codecs module to decode and save the zen into a string.

  3. Use .splitlines() method to convert this string into lines.

  4. Use slicing ([2:]) to discard the first 2 lines (header and blank line).

  5. Use enumerate() to also get a line counter going (you can start it at 1 using like-named optional argument).

  6. I then use format() to interpolate the variables into a template string (SHORT_TITLE).

I love how expressive Python is! 🐍 😍

#contextlib #codecs #zen #enumerate #format