How can I return python's "import this" as a string?

python function return variable
python return string
return in python 3
python function return multiple values
python return nothing
if return python
how to use return value in another function python
python function return list

Typing

import this 

will return the Zen of Python, but nowhere do I seem to be able find a solution about how to set it equal to a string variable which I can use further on in my code...

You can temporarily redirect stdout to a StringIO instance, import this, and then get its value.

>>> import sys, cStringIO
>>> zen = cStringIO.StringIO()
>>> old_stdout = sys.stdout
>>> sys.stdout = zen
>>> import this
>>> sys.stdout = old_stdout
>>> print zen.getvalue()
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

This code works on python2.7 -- for python 3, use io.StringIO instead of cStringIO.StringIO, and also have a look at contextlib.redirect_stdout which was added in 3.4. That would look like this:

>>> import contextlib, io
>>> zen = io.StringIO()
>>> with contextlib.redirect_stdout(zen):
...    import this
...
>>> print(zen.getvalue())

Python Tutorial: Functions, Introduction to functions in Python with and without parameters. A return statement ends the execution of the function call and "returns" the result, i.e. the value  Return Statement; Python Docs. All functions return a value when called. If a return statement is followed by an expression list, that expression list is evaluated

Let's look at what this.py does:

s = "some encrypted string"
d = a map to decrypt the string

print "".join([d.get(c, c) for c in s])

Let's note that the encryption is just ROT13.

So if we really wanted to grab the string, we could do:

import this
s = this.s.decode('rot13')

Or, to explicitly follow the style of the this.py module...

import this
s = "".join([this.d.get(c, c) for c in this.s])

Python Return Statement, All functions return a value when called. If a return statement is followed by an expression list, that expression list is evaluated and the value is returned: >>> def​  In the given code the value returned (that is 2) when function foo () is called is used in the function bar (). These return values are printed on console only when the print statements are used as shown below. We see that when foo () is called from bar (), 2 isn't written to the console.

I think the accepted answer is overcomplicated for this case (while very interesting for capturing the standard output in general).

In Python 3, you can get the Zen of Python as a string by simply doing:

import this
import codecs

zen_of_python = codecs.encode(this.s, 'rot13')

6.7 The return statement, return may only occur syntactically nested in a function definition, not within a nested class definition. If an expression list is present, it is evaluated, else None is  In Python, you can return multiple values by simply return them separated by commas. As an example, define a function that returns a string and a number as follows: Just write each value after the return , separated by commas.

the string is stored in this.s, but that's funny, because it's encrypted:

>>> help(this)
NAME
    this

FILE
    /usr/lib/python2.7/this.py

MODULE DOCS
    http://docs.python.org/library/this

DATA
    c = '!'
    d = {'A': 'N', 'B': 'O', 'C': 'P', 'D': 'Q', 'E': 'R', 'F': 'S', 'G': ...
    i = 25
    s = "Gur Mra bs Clguba, ol Gvz Crgref\n\nOrnhgvshy vf o...bar ubaxvat ...

$ head /usr/lib/python2.7/this.py
s = """Gur Mra bs Clguba, ol Gvz Crgref

Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcnefr vf orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.

Why would you use the return statement in Python?, The print() function writes, i.e., "prints", a string or a number on the console. The return statement does not print out the value it returns when the  Functions can display data directly in Python or they can return the data to the caller so that the caller can do something more with it. In some cases, a function displays data directly as well as returns data to the caller, but it’s more common for a function to either display the data directly or to return it to the caller.

Python return Statement, Python return Statement. The python return statement is used in a function to return something to the caller  Return is the reserved word in Python. It says that we should return the parameter which the fuctions is supposed to be returned when it was called . Once it was returned , the next lines of code are not executed in the method or function . We can return any data type in Python .

What is the purpose of the return statement?, Python will actually insert a return value for you if you decline to put in your own, it's called "None", and it's a special type that simply means nothing, or null. In Python, we can return multiple values from a function. Following are different ways. 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. # A Python program to return multiple. # values from a method using class.

8. Global & Return, You might have encountered some functions written in python which have a return keyword in the end of the function. Do you know what it does? It is similar to  There are so many ways we can return a list from a python function. One such function is given below.Exampledef retList(): list = [] for i in range(

Comments
  • this is a module. Look at the source code of that module to see what it contains. That should get you started.
  • this defines 4 names (c, d, i and s) - you can actually get the text using only two of them
  • I definitely think this is the most appropriate approach for answering the question. It's generalizable to other modules that happen to have printed output and it's resistant to implementation changes to the this module. The other answers, while they work, are so specific that we might as well tell the OP to copy the text themselves and paste it into a string literal, or link to the on-line version of PEP 20, etc. If the OP is trying to understand how it works, then what they really want is this: stackoverflow.com/questions/5855758
  • The problem with using import this this way is it also prints out the Zen message, which probably isn't wanted.
  • The problem with using import this this way is it also prints out the Zen message, which probably isn't wanted.
  • The dict translates the letters to something readable, but there's some weird mojo going on in this module.
  • The letters are shifted alphabetically by some characters: stackoverflow.com/questions/5855758/…
  • Yeah, opened the module up in PyCharm and the magic was gone. It was more fun when I thought there was a sinister plot afoot.