Python Print Statement
In Python, a print statement is just a programmer-friendly tool. Interface to the standard output stream. From a technical point of view, this instruction converts objects to text view and either sends the result to standard output or passes to another file-like object. The python print statement is tightly coupled with the concept of files and streams in Python.
Since the standard output stream in Python is available as an object stdout from the built-in sys module (that is, sys.stdout), it is quite possible to simulate modify the behavior of the python print statement using the file write methods, although using print looks simpler.
The output operation is one of the differences between Python 3.0 and 2.6 were the most visible. In fact, the differences in the implementation of these operations are one of the main reasons for the impossibility performance of programs written for version 2.X under control version 3.X without changes to the program code. In particular, from the version the interpreter depends on how the print operation is formatted:
- In Python 3.X, the print statement has become a built-in function that takes named arguments that define special functions. output presses.
- In Python 2.X, print is a statement that has its own characteristic syntax.
we will look at the features of the print implementation in each of them separately. If you are lucky enough to work with programs written for one version Python, you can only read the section that is appropriate for your case. However, your situation may change, so it won’t be superfluous for you to get acquainted with both versions.
the print function in Python 3.0
Strictly speaking, print is not a kind of statement in version 3.0, this is just one of the expression instructions that we have seen in the previous section.
Usually, the call to the built-in print function is formatted as a separate line, because it does not return any value (more precisely, it returns a None object), which would be worth taking care of. Since in version 3.0 print is a regular function, not some kind of a special form, but the standard syntax for calling functions. Due to this special modes of operation are defined using named arguments. This form is not only more versatile but also provides better I have support for future extensions.
By comparison, the python print statement in version Python 2.6 has specialized syntax supporting features such as suppressing line termination and redirecting output to a file. In addition, the instruction print in 2.6 does not allow you to define delimiter strings at all; in 2.6 you are much more likely to have to construct strings in advance than in 3.0.
Python print statement Calling format:
The syntax for calling the print function in version 3.0 is as follows:
print ([object, ...] [, sep = ’’] [, end = ’\ n’] [, file = sys.stdout])
The items in square brackets here are optional and can be omitted, and the values following the = sign determine the values by default. Simply put, this built-in function outputs to file stream one or more objects in a text representation, separated by the string sep and ends the output with the end.
The sep, end, and file parameters, if required, should not be passed in the form of positional, and in the form of named arguments, that is, using by using the special name = value syntax. Named arguments can be specified in any order in the call functions, but after the objects intended for output, and define the parameters output dimensions:
- sep is the string to be inserted between objects in the output. The default is one space. To suppress the output of the delimiter string, pass an empty string in this argument.
- the end is a string added to the end of the displayed text. Contains the end-of-line character \ n by default. If you pass an empty string in this argument, the next call to the print function will start printing text from the position where the current line ended.
- file a file object, standard stream, or another object similar to the file where the text will be output. The default is the object ys.stdout standard output stream. This argument can be passed an object that supports the write (string) file method; if passes The actual file object must already be open for writing.
The textual representation of any object that is passed for output, the print function gets it using the str built-in function. As we already know, this function returns a human-readable string representation of any object.1 When called with no arguments, the print function will simply print out the character end of the line to standard output, which looks like the output is empty strings.
The print function in action:
Using the print function in version 3.0 is much easier than it could be I would assume after getting acquainted with some of its features. To illustrate, let’s take a few short examples. The following shows the order in which objects of various types are output to the default standard output stream, with a default separator line and a line terminator appended (these output parameter values were default values because they are used overwhelmingly in most cases):
>>> print () # Prints an empty string >>> x = ‘spam’ >>> y = 99 >>> z = [‘eggs’] >>> >>> print (x, y, z) # Prints three objects spam 99 [‘eggs’]
In this example, there is no need to convert objects. to strings, as required by the methods for writing to files. The default function print prints a space character between objects. To suppress whitespace, simply pass an empty string in the sep named argument or specify another string separator:
>>> print (x, y, z, sep = '') # Separator line will not be printed spam99 [‘eggs’] >>> >>> print (x, y, z, sep = ’,’) # Custom separator string spam, 99, [‘eggs’]
In addition, the print function adds an end character at the end of the output line. strings. The output of this character can be suppressed by passing an empty string to the named argument end. Similarly, you can pass a different one in this argument. line separator (including the \ n character to manually provide translation lines):
>>> print (x, y, z, end = '') # Suppress end-of-line character output spam 99 [‘eggs’] >>> >>> >>> print (x, y, z, end = ''); print (x, y, z) # Print two lines on one line spam 99 [‘eggs’] spam 99 [‘eggs’] >>> print (x, y, z, end = ’... \ n’) # Custom line separator spam 99 [‘eggs’] ... >>>
The simultaneous use of named arguments defining separators between objects in a line and between lines can be specified in any order, but only after the objects that you want to display:
>>> print (x, y, z, sep = ’...’, end = ’! \ n’) # Multiple named arguments spam ... 99 ... [‘eggs’]! >>> print (x, y, z, end = ’! \ n’, sep = ’...’) # The order does not matter spam ... 99 ... [‘eggs’]!
The following demonstrates how to use the named argument file. It can be used to redirect the output of text to a file open for writing, or to another object compatible with the output operation (in fact, this is a kind of stream redirection, which will be discussed below in this section):
>>> print (x, y, z, sep'...', file'.txt', 'w')) >>> print (x, y, z) q Output in stdout thread spam 99 [‘eggs’] >>> print ('.txt'). spam... 99...[‘eggs’]
Finally, keep in mind that the ability to identify a divider line and the line divider provided by print is just handy. If you need to get more complicated formatting doesn’t have to take advantage of this opportunity. In the world, hundred of these can be designed in advance or resort to help formatting tools, inside call the print function, and bring out the line that’s just Print call:
>>> text = ‘%s: %-.4f, %05d’ % (‘Result’, 3.14159, 42) >>> print(text) Result: 3.1416, 00042 >>> print (‘% s:% -. 4f,% 05d’% (‘Result’, 3.14159, 42)) Result: 3.1416, 00042
As we will see in the next section, almost everything that has been said about the print function in Python 3.0, the same applies to the python print statement in version 2.6, especially when you consider that the function was intended as further development and improvement of support for withdrawal operations in 2.6.
The print function in Python 2.6:
As mentioned above, the output operation in Python 2.6 is implemented as instructions with a unique and very specific syntax, not in the form built-in function. In practice, is printing? organized in 2.6 is a variation on the same theme – except for the delimiter lines (which are kept in version 3.0 and are not supported in version 2.6), for all other print functions in version 3.0 have direct analogs in the print structures in version 2.6.
Table 1 lists the forms of the python print statement in Python 2.6 and the equivalent of their print calls in Python 3.0. Note that the comma in the python print statement is essential – it separates objects that are required to be printed and the trailing comma suppresses the output of the end line, which is usually displayed at the end of a line of text (do not confuse with the syntax of tuples!). The syntax >> is commonly used as a bitwise right shift operator, however, it can be used in print statements to define an output stream other than sys.stdout, which is the default.
Table 1: List of python print statement forms
|Print statement in Python 2.6||Equivalent in Python 3.0||Interpretation|
|print x, y
|Outputting objects to sys.stdout; adds a space between objects and end symbol strings|
|print x, y,
|print(x, y, end=’’)
|The same, only for this times the end-of-line character is not added|
|print >> afile, x, y
|print(x, y, file=afile)
|The text is passed to the method myfile.write, not sys.stdout.write|
The python print statement in action:
Although the syntax for the print statement in Python 2.6 is different from the syntax for the print function in Python 3.0, it is just as easy to use. Let’s take a look at some simple examples. Default statement print in python 2.6 adds a space between items separated by commas and a line break at the end of the current line of output:
>>> >>> x = ‘a’ >>> y = ‘b’ >>> print x, y a b
This formatting is just the default that you can use or not. To suppress the output of the end-of-line character (and later continue outputting text to the current line), the python print statement should be terminated with a comma character, as shown in the second line of table 1 (below the there are two statements on one line, separated by semicolons):
>>> print x, y,; print x, y a b a b
To suppress whitespace between items, output not in this way, instead, you need to independently assemble the string with by the power of the concatenation and formatting operation, and print this line:
>>> print x + y ab >>> print ‘%s...%s’ % (x, y) a...b
As you can see from the examples, except for the special syntax for defining personal output modes, the python 2.6 print statement is almost as simple in use, just like the print function in 3.0. The next section describes how to redirect output to a file using the print statement in python 2.6.
Redirecting an Output Stream in Python Print Statement:
In both Python 3.0 and 2.6, the output text is sent to standard output by default. However, quite often it becomes necessary to output the text to some other place, for example, to a file, so that save the results for later use or for testing purposes. Such output redirection can be organized at the level system command shell, outside of the interpreter, however, governance within a script is no more complicated.
Hello world Python program:
Let’s start with the familiar (and common) test of the programming language with the “hello world” program. To display the message “hello world” in a program on in Python, just print the line:
>>> print (‘hello world’) # Call a string object in 3.0 hello world >>> print 'hello world' # Call string object in 2.6 hello world
Since the results of expressions in the interactive shell are displayed automatically mathematically, you may not even use the python print statement just type the expression that you want to output, and the result of its evaluation immediately will be outputted:
>>> ‘hello world’ # Interactive shell prints output automatically ‘Hello world’
This fragment can hardly be called an example of a programming skill, so no less, it clearly demonstrates the features of the behavior of the output operation. In reality, the python print statement is just an ergonomic feature of the Python language – it provides a simple interface to the sys.stdout object, adding a minor amount of formatting. In fact, if you like going the harder way, you can program the output so in this way:
>>> import sys # Output in a more complex way >>> sys.stdout.write (‘hello world \ n’) hello world
This snippet explicitly calls the write method of the sys.stdout attribute, preset by the Python interpreter when opening a file associated with an output stream. The python print statement hides most of these details, providing a simple tool for solving simple tasks withdrawal.
Redirecting the output stream manually:
So why did I show a more complex way of output? As it turns out, the object sys.stdout provides output functionality equivalent to the basic Python methodology. Generally speaking, the python print statement and the object sys.stdout are related as following statement:
print (X, Y) # Or print X, Y in 2.6 is equivalent to the longer one: import sys sys.stdout.write (str (X) + ‘’ + str (Y) + ‘\ n’)
which manually converts the object to a string with function str, appends the end-of-line character using the + operator, and calls The write method of the output stream. How would you accomplish the same task? (By this with an example I would like to emphasize the friendly nature of the print statement…)
Obviously, the longer form itself is less convenient to use. However, it is good to know that it is the exact equivalent of the instruction print because it is possible to reassign sys.stdout to something other than the standard output stream. In other words, this equivalent valence provides the ability to force the print statement to output text to another location. For example:
import sys sys.stdout = open (‘log.txt’, ‘a’) # Redirect output to file ... Print (x, y, x) # Text will appear in log.txt file
Here we have manually redirected the sys.stdout object to a file opened manually in add mode (as we add new content). After this, all print statements in the program will print text to the end of the file log.txt instead of stdout. Print statements successfully must call the sys.stdout object’s write method no matter where it is referring to. Since there is only one sys module in each process, redirecting sys.stdout in this way will affect all the print structure in the program.
In fact, as will be discussed in the next sidebar describing the python print statement and the stdout object, it is possible to redirect sys.stdout to an object that isn’t even a file, provided it supports the expected interface: a write method that takes a string argument. This object can be a class capable of handling and transferring edit the displayed text in any way.
This technique of redirecting the output stream is primarily useful in programs that were originally designed to use the print statement. If you know that all output should be sent to a file, you can always organize the call of methods for writing to a file. When redirecting an output stream in instruction-based programs print, setting up the sys.stdout object provides a convenient alternative to change the behavior of all print statements or use redirection system command shell tools.
Automatic stream redirection:
Accepting redirection of text output by assigning a file to an object sys.stdout is very often used in practice. However, in the program code the previous section has one potential problem – missing a direct way to restore the original output stream, if suddenly, after outputting data to a file, you need to return back to the output on the screen. But since sys.stdout is a regular object, you can always save it and restore it later if necessary:
>>> import sys >>> temp = sys.stdout # Save for later recovery >>> sys.stdout = open (‘log.txt’, ‘a’) # Redirect output to file >>> print (‘spam’) # Will print to file, not to screen >>> print (1, 2, 3) >>> sys.stdout.close () # Pop buffers to disk >>> sys.stdout = temp # Restore original stream >>> print (‘back here’) # Display back here >>> print (open (‘log.txt’). read ()) # Results of earlier calls spam # to the print statement
The need for such redirection arises surprisingly often, and manual Retention and restoration of the original output flow is a procedure for precisely complex, which led to an extension for the print statement, which makes such a redirection unnecessary. In version 3.0, the name file argument allows you to redirect to the file the only print call without resorting to reinstalling the sys.stdout value. Since this redirection is temporary, the usual print calls continue to display the text in the original output stream. In version 2.6, the same effect can be achieved by pointing out at the beginning print statement >> characters and after them is a file object (or another compatible object). For example, the next snippet displays text in the log file. Txt:
log = open (‘log.txt’, ‘a’) # 3.0 print (x, y, z, file = log) # Print to a file-like object print (a, b, c) # Print to original output stream log = open (‘log.txt’, ‘a’) # 2.6 print >> log, x, y, z # Output to a file-like object print a, b, c # Print to original output stream
These redirection methods are useful when you need to organize output to both a file and standard output in the same program. However, if you are going to use these forms of output, you will need to create a file object (or an object that has a write method, just like an object file) and pass the instructions to this object, not a string with the file name:
>>> log = open (‘log.txt’, ‘w’) >>> print (1, 2, 3, file = log) # In 2.6: print >> log, 1, 2, 3 >>> print (4, 5, 6, file = log) >>> log.close () >>> print (7, 8, 9) # In 2.6: print 7, 8, 9 7 8 9 >>> print (open (‘log.txt’). read ()) 1 2 3 4 5 6
These extended forms of the python print statement are often used to print error messages to standard error, sys.stderr. You can either use its write method and format the outputted lines manually or use the redirection syntax:
>>> import sys >>> sys.stderr.write ((‘Bad!’ * 8) + ‘\ n’) Bad! Bad! Bad! Bad! Bad! Bad! Bad! Bad! >>> print (‘Bad!’ * 8, file = sys.stderr) # In 2.6: print >> sys.stderr, ‘Bad’ * 8 Bad! Bad! Bad! Bad! Bad! Bad! Bad! Bad!
Now that you know all about output redirection, the equivalence of the print function and the write method of files should seem obvious to you. The following example demonstrates the output of text in both ways in version 3.0, then redirecting the output to an external file is demonstrated and the contents of the text files are checked:
>>> X = 1; Y = 2 >>> print (X, Y) # Output: easy way 12 >>> import sys # Conclusion: the hard way >>> sys.stdout.write (str (X) + ‘’ + str (Y) + ‘\ n’) 12 4 >>> print (X, Y, file = open (‘temp1’, ‘w’)) # Redirect to file >>> open (‘temp2’, ‘w’). write (str (X) + ‘’ + str (Y) + ‘\ n’) # Write to file 4 >>> print (open (‘temp1’, ‘rb’). read ()) # Binary mode b'1 2 \ r \ n ' >>> print (open (‘temp2’, ‘rb’). read ()) b'1 2 \ r \ n '
As you can see, it is better to use print to display text, unless you really enjoy keyboard input. This is an example demonstrating the equivalence of using the print operation and the write method of files, an example of imitating the print function for Python 2.6.