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))
-
Use
contextlib.redirect_stdout(...
to mute console output of the "import this" statement. -
Use the
codecs
module to decode and save the zen into a string. -
Use
.splitlines()
method to convert this string into lines. -
Use slicing (
[2:]
) to discard the first 2 lines (header and blank line). -
Use
enumerate()
to also get a line counter going (you can start it at 1 using like-named optional argument). -
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