Python Print Functions
The basic print function in Python prints a string or a series of characters to the standard output -- usually the console you are using to call the program. You can also use it to print these characters to a file. The correct syntax for calling the print function depends on the version of Python you are using.
-
Print Statement
-
Deprecated in version family 3.x but still in use in 2.x, the print statement is the simplest way of printing a string to the console output. "Print" is a special keyword, like "return" and "try." By default, this statement prints the given object to the standard output. The syntax is as follows:
print [>> target], [string or character]
By default, Python prints the object and then prints a line terminator, "\n." If you end the print statement with a comma, it will not print the line terminator. You can also specify a target file to write through by using the ">>" string and a comma after the file pointer.
Print Function
-
In version family 3.x, the print statement was replaced by the print function introduced in version 2.6 (Reference 1). The print function works like any other function, and you call it with the following syntax:
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])
All arguments are optional; using no arguments prints an empty line to the console. "Sep" separates the components of the object with the given character. "End" specifies the character to print at the end -- by default, a newline character, but you can also use an empty string to signify the lack of a new line. Finally, including the "file" parameter allows you to specify a file to write to.
-
Functions Also Used for Printing
-
Some special functions work in conjunction with print functions to provide full functionality to Python. "File.write()" is a function that writes a string of characters to the given file; calling it using "sys.stdout" as the file will perform the same function as a print statement or function. "Repr(object)" is a function often used in conjunction with a print statement -- it converts the given object into a printable string.
Print Examples
-
#prints "Hello, Python!" and a newline character
print "Hello, Python!" #Version 2 only
print("Hello, Python!") #Version 2 and 3#prints the contents of array 'arr' with each array entry separated by a comma
print ", ".join(arr) #Version 2 only
print (arr, sep=",") #Version 2 and 3#prints "Hello, Python!" to a file given by the name "fileptr"
print >> fileptr, "Hello, Python!" #Version 2 only
print ("Hello, Python!", file=fileptr) #Version 2 and 3
-