In Python 3.x
, you can assign print()
statement to the variable like this:
>>> var = print('some text')
some text
>>> var
>>> type(var)
<class 'NoneType'>
According to the documentation,
All non-keyword arguments are converted to strings like str()
does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None
, which means to use the default values. If no objects are given, print() will just write end.
The file argument must be an object with a write(string)
method; if it is not present or None
, sys.stdout
will be used. Since printed arguments are converted to text strings, print()
cannot be used with binary mode file objects. For these, use file.write(...)
instead.
That's why we cannot assign print()
statement values to the variable. In this question you have ask (or any function)
. So print()
also a function with the return value with None
. So the return value of python function is None
. But you can call the function(with parenthesis ()) and save the return value in this way.
>>> var = some_function()
So the var
variable has the return value of some_function()
or the default value None
. According to the documentation about print()
, All non-keyword arguments are converted to strings like str() does and written to the stream
. Lets look what happen inside the str()
.
Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str()
depends on whether encoding or errors is given, as follows.
So we get a string object, then you can modify the below code line as follows,
>>> var = str(some_function())
or you can use str.join()
if you really have a string
object.
Return a string which is the concatenation of the strings in iterable. A TypeError
will be raised if there are any non-string values in iterable, including bytes
objects. The separator between elements is the string providing this method.
change can be as follows,
>>> var = ''.join(some_function()) # you can use this if some_function() really returns a string value