Python Language Incompatibilities moving from Python 2 to Python 3 Print statement vs. Print function

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

In Python 2, print is a statement:

Python 2.x2.7
print "Hello World"
print                         # print a newline
print "No newline",           # add trailing comma to remove newline 
print >>sys.stderr, "Error"   # print to stderr
print("hello")                # print "hello", since ("hello") == "hello"
print()                       # print an empty tuple "()"
print 1, 2, 3                 # print space-separated arguments: "1 2 3"
print(1, 2, 3)                # print tuple "(1, 2, 3)"

In Python 3, print() is a function, with keyword arguments for common uses:

Python 3.x3.0
print "Hello World"              # SyntaxError
print("Hello World")
print()                          # print a newline (must use parentheses)
print("No newline", end="")      # end specifies what to append (defaults to newline)
print("Error", file=sys.stderr)  # file specifies the output buffer
print("Comma", "separated", "output", sep=",")  # sep specifies the separator
print("A", "B", "C", sep="")     # null string for sep: prints as ABC
print("Flush this", flush=True)  # flush the output buffer, added in Python 3.3
print(1, 2, 3)                   # print space-separated arguments: "1 2 3"
print((1, 2, 3))                 # print tuple "(1, 2, 3)"

The print function has the following parameters:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

sep is what separates the objects you pass to print. For example:

print('foo', 'bar', sep='~') # out: foo~bar
print('foo', 'bar', sep='.') # out: foo.bar

end is what the end of the print statement is followed by. For example:

print('foo', 'bar', end='!') # out: foo bar!

Printing again following a non-newline ending print statement will print to the same line:

print('foo', end='~')
print('bar')
# out: foo~bar

Note : For future compatibility, print function is also available in Python 2.6 onwards; however it cannot be used unless parsing of the print statement is disabled with

from __future__ import print_function

This function has exactly same format as Python 3's, except that it lacks the flush parameter.

See PEP 3105 for rationale.



Got any Python Language Question?