< BACKMake Note | BookmarkCONTINUE >
152015024128143245168232148039199167010047123209178152124239215162146122163094222089189188

Input and Output

Python, as any other language, provides means to get input from the user and also to display information to him.

Let's see how we can handle it.

					
>>> x = input ("type anything: ")
>>> print "You have typed ", x

				

Note that the input prompt can be anything, even an empty one.

If the user types 5, x is properly treated as a number. To make x become a string, the user must explicitly type the quotes.

To avoid this problem, you can use the raw_input function:

					
>>> x = raw_input ("type anything: ")
>>> print "You have typed ", x

				

Now, it doesn't matter whether the user types the quotes.

Note that the print command requires objects to be separated by commas:

					
>>> print "parrot", "sketch"
parrot sketch

				

Displaying Information

Let's delve a little bit deeper into this topic.

Python has three standard file objects, which are available from the sys module. The interpreter uses them to provide input and output facilities. (Refer to Chapter 3, "Python Libraries," for details and examples—the sys module.)

They are known as sys.stdin, sys.stdout, sys.stderr

print statements are mapped to the sys.stdout. Hence, they send the textual representation of objects to the standard output stream:

						
>>>import sys
>>>sys.stdout.write("Nudge-nudge\n")
Nudge-nudge

					

Did you know that it is possible to re-map the standard output device?

Yes, that is possible.

You can run the following code to write to a file:

						
>>> sys.stdout = open("outputtest.txt", "w")
>>> print "hello"
>>> sys.stdout.close

>>> sys.stdout = sys.__stdout__
>>> sys.exit()

					

Note that sys.__stdout__ stores the original stdout.

The last line restores the sys.__stdout__ original value to such an extent that new print statements will display onscreen, instead of being sent to a file.

As additional information, this program uses sys.exit() to quit its execution (refer to Chapter 3 for details).

Starting with release 2.0, the print statement can have its output directed to a file-like object, as it is demonstrated in the following example.

						
print >> sys.stderr, "Sorry, you cannot do that!"

					

Formatting Operations

Python provides formatting operations similar to the printf() function from the C language.

Take a look at the following example:

						
>>> print "Mr. Lumberjack! do not sing!"

					

What if you don't want to hard-code the name inside the string? Compare the previous line of code against the following one:

						
>>> print "Mr. %s, do not sing!" % someone

					

Flexible, don't you think? And by the way, the order of the elements doesn't affect the final result.

Therefore, saying

						
>>> print "Mr. %s" % someone

					

is the same as saying

						
>>> print someone % "Mr. %s"

					

As a matter of fact, the following example shows how Python handles multiple format arguments. Note that you need to provide a tuple of values to fill the position indicated by the formatting operators (see Table 2.2).

						
>>> print "The %s has %i wings" % ("parrot", 2)

					

Table 2.2. Formatting Operators Table
Formatting Operator Description
%d decimal integer
%i decimal integer
%u unsigned integer
%o octal integer
%x hexadecimal integer
%X hexadecimal integer (uppercase letters)
%f floating point as [-]m.dddddd
%e floating point as [-]m.dddddde±xx
%E floating point as [-]m.ddddddE±xx
%g, %G floating point where the exponent is less than -4 or greater than the precision
%s any printable object (such as strings)
%c a single character
%% the literal %

The following code is another simple example:

						
>>> value = 14
>>> print "The value is %d" % value
The value is 14

					

Next, you will see some special ways to format operations by putting special characters between the % literal and the formatting operator. Before going through the examples, we need to initialize some variables.

						
>>> intg = 42
>>> fltn = 13.142783
>>> strg = "hello"
>>> dict = {"xx":13, "yy":1.54321, "zz":"parrot"}

					
  • You can use dictionary key names in parentheses.

    								
    >>> print "%(zz)s" % dict
    parrot
    
    							
  • By using the - literal, you can left align the string block.

    								
    >>> print "%-8dend" % fltn
    "13       end"
    
    							
  • By using the + literal, you can show positive and negative numerical signs.

    								
    >>> print "%+d" % intg
    +42
    
    							
  • If you insert a zero, you will get a zero-filling.

    								
    >>> print "%08d " % intg
    "0000042"
    
    							
  • Maximum field width (strings)

    								
    >>> print "%0.2s" % strg
    "he"
    
    							
  • Period (.) + precision (floating-point numbers)

    								
    >>> print "%0.2f" % fltn
    13.14
    
    							
  • Minimum number of digits (integer)

    								
    >>> print "%0.10f" % intg
    0000000042
    
    							

Tip

A * can be used in the place of any number. It uses the next value that matches that format in a tuple.

							
>>> print "%*.*f" % (5,3,2.45)
2.450
					
						



Note

Python 2.0 contains a new format string called %r, which prints the repr() value of the given argument. You can clearly see the difference between %r and %s by looking at the following example.

							
'%r %s'% ('Python', 'Python')

						

returns the string

							
'Python'Python

						




Last updated on 1/30/2002
Python Developer's Handbook, © 2002 Sams Publishing

< BACKMake Note | BookmarkCONTINUE >

Index terms contained in this section

%% formatting operator
%c formatting operator
%d formatting operator
%e formatting operator
%E formatting operator
%f formatting operator
%g formatting operator
%G formatting operator
%i formatting operator
%o formatting operator
%r format string
      comparing with %s format string
%s format string
      comparing with %r format string
%s formatting operator
%u formatting operator
%x formatting operator
%X formatting operator
* (asterisk)
      replacing numbers with
asterisks (*)
      replacing numbers with
comparing
      %r and %s format strings
displaying
      input and output
format strings
     %r and %s
            comparing
formatting operations 2nd
input
      users 2nd 3rd
modules
      sys
numbers
      replacing with asterisks (*)
operations
      formatting 2nd
output
      print statements
      users 2nd 3rd
print statement
print statements
      output
replacing
      numbers with asterisks (*)
statements
      print
            output
strings
     format
            %r and %s, comparing
sys module
tuples
      replacing numbers with asterisks (*)
users
      input and output 2nd 3rd
viewing
      input and output

© 2002, O'Reilly & Associates, Inc.