Python Input And Output

Output Formatting

Two ways to format your output:

  1. Do all the string handling.
  2. Use the str.format() method

String formatting

  • The str() function returns representations of values which are human-readable.

*The repr() function returns representation which can be read by the interpreter.

Example

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(0.1)
'0.1'
>>> repr(0.1)
'0.10000000000000001'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print s
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print hellos
'hello, world\n'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"

Files

  • open() returns a file object, and is most commonly used with two arguments: open(filename, mode).
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.